首页 > 其他 > 详细

二叉树的前序遍历

时间:2019-07-29 14:04:32      阅读:98      评论:0      收藏:0      [点我收藏+]

二叉树前序遍历,分为递归方法和非递归方法:

递归:

private static List<Integer> preList = new ArrayList<>();
public static List<Integer> preorderTraversalRec(TreeNode root){
    if (null == root){
        return preList;
    }
    preorder(root);
    return preList;
}
private static void preorder(TreeNode root){
    if (null == root){
        return;
    }
    preList.add(root.val);
    preorder(root.left);
    preorder(root.right);
}

非递归:

public static List<Integer> preorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if (null == root){
        return list;
    }
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()){
        TreeNode node = stack.pop();
        list.add(node.val);
        if (null != node.right){
            stack.push(node.right);
        }
        if (null != node.left){
            stack.push(node.left);
        }
    }
    return list;
}

 

二叉树的前序遍历

原文:https://www.cnblogs.com/earthhouge/p/11262901.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!