【每日一题-leetcode】144.二叉树的前序遍历

144.二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]

1


 2
/

3

输出: [1,2,3]

1.递归法

 public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList();
            helper(root,result);
            return result;
        }
    
        public static void helper(TreeNode root,List<Integer> result){
            if(root!=null){
                //根
                result.add(root.val);
                //左
                if(root.left != null){
                    helper(root.left,result);
                }
                //右
                if(root.right != null){
                    helper(root.right,result);
                }
            }
        }

2.基于栈的遍历

其实我们使用递归去输出二叉树的遍历,计算机也是利用栈进行操作,我们可以模拟栈进行操作、

栈是先进后出的线性结构。因此 前序遍历是根左右 应该先push rootNode 输出。剩下就是左右节点的遍历,应该先push右节点,然后在push左节点,这样在pop的时候 顺序就是左右。

时间复杂度:O(n) 相当于树进行了一次loop操作

空间复杂度:O(n) 用栈做临时空间存储。

   public List<Integer> preorderTraversal(TreeNode root) {
            if(root == null){
                return new ArrayList();
            }
    
            List<Integer> result = new ArrayList();
            Stack<TreeNode> stack = new Stack();
    
            //先将头结点条件进去
            stack.push(root);
    
            while(!stack.isEmpty()){
                TreeNode node = stack.pop();
                result.add(node.val);
                //添加右节点 因为栈是先进后出 而前序遍历是根左右 所以右节点陷进去最后出来
                if(node.right != null){
                    stack.push(node.right);
                }
                //添加左节点 
                if(node.left != null){
                    stack.push(node.left);
                }
    
            }
            return result;
        }
原文地址:https://www.cnblogs.com/qxlxi/p/12860685.html