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

94.二叉树的中序遍历

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

示例:

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

1


 2
/

3

输出: [1,3,2]

1.递归法

我们知道二叉树的遍历有前序遍历 中序遍历 后序遍历。
前序遍历 :根左右
中序遍历:左根右
后序遍历:左右根
时间复杂度:O(n)。递归函数 T(n) = 2*T(n/2)+1
空间辅助度:最坏情况下需要空间O(n),平均情况为O(log N)

 public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList();
        helper(root,result);
        return result;
    }

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

2.基于栈的遍历

用一个栈接收访问的路径 因为栈是先进后出 所以最后访问的元素就是最先遍历的元素。先查找左节点 左节点完毕后 输出,查找右节点。
时间复杂度:O(n)
空间复杂度:O(n)

 public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        //获取根节点 
        TreeNode curr = root;
        //如果当前节点不为null or 栈不为null 说明还有节点没有遍历完
        while(curr != null || !stack.empty()){
            //先将左节点push 进
            if(curr!=null){
                stack.push(curr);
                curr = curr.left;
            }
            //后push的 先输出
            curr = stack.pop();
            result.add(curr.val);
            //查看当前节点的右节点 
            curr = curr.right;
        }

        return result;
    }
原文地址:https://www.cnblogs.com/qxlxi/p/12860686.html