【力扣算法】94-二叉树的中序遍历

题目

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

示例:

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

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

方法一:递归

第一种解决方法是使用递归。这是经典的方法,直截了当。我们可以定义一个辅助函数来实现递归。

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

    public void helper(TreeNode root, List < Integer > res) {
        if (root != null) {
            if (root.left != null) {
                helper(root.left, res);
            }
            res.add(root.val);
            if (root.right != null) {
                helper(root.right, res);
            }
        }
    }
}

复杂度分析

时间复杂度: O ( n ) O(n) 。递归函数 T ( n ) = 2 T ( n / 2 ) + 1 T(n) = 2 \cdot T(n/2)+1
空间复杂度:最坏情况下需要空间 O ( n ) O(n) ,平均情况为 O ( log n ) O(\log n)

方法二:基于栈的遍历

本方法的策略与上衣方法很相似,区别是使用了栈。

下面是示例:

public class Solution {
    public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        Stack < TreeNode > stack = new Stack < > ();
        TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            res.add(curr.val);
            curr = curr.right;
        }
        return res;
    }
}

复杂度分析

时间复杂度:O(n)。

空间复杂度:O(n)。

方法三:莫里斯遍历

本方法中,我们使用一种新的数据结构:线索二叉树。方法如下:

Step 1: 将当前节点current初始化为根节点

Step 2: While current不为空,

若current没有左子节点

a. 将current添加到输出

b. 进入右子树,亦即, current = current.right

否则

a. 在current的左子树中,令current成为最右侧节点的右子节点

b. 进入左子树,亦即,current = current.left

举例而言:

      1
    /   \
   2     3
  / \   /
 4   5 6

首先,1 是根节点,所以将 current 初始化为 1。1 有左子节点 2,current 的左子树是

     2
    / \
   4   5

在此左子树中最右侧的节点是 5,于是将 current(1) 作为 5 的右子节点。令 current = cuurent.left (current = 2)。 现在二叉树的形状为:

     2
    / \
   4   5
        \
         1
          \
           3
          /
         6

对于 current(2),其左子节点为4,我们可以继续上述过程

    4
     \
      2
       \
        5
         \
          1
           \
            3
           /
          6

由于 4 没有左子节点,添加 4 为输出,接着依次添加 2, 5, 1, 3 。节点 3 有左子节点 6,故重复以上过程。 最终的结果是 [4,2,5,1,6,3]。

了解更多细节请查阅 线索二叉树 与 莫里斯方法解析

class Solution {
    public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        TreeNode curr = root;
        TreeNode pre;
        while (curr != null) {
            if (curr.left == null) {
                res.add(curr.val);
                curr = curr.right; // move to next right node
            } else { // has a left subtree
                pre = curr.left;
                while (pre.right != null) { // find rightmost
                    pre = pre.right;
                }
                pre.right = curr; // put cur after the pre node
                TreeNode temp = curr; // store cur node
                curr = curr.left; // move cur to the top of the new tree
                temp.left = null; // original cur left be null, avoid infinite loops
            }
        }
        return res;
    }
}

复杂度分析

时间复杂度:O(n)。 想要证明时间复杂度是O(n),最大的问题是找到每个节点的前驱节点的时间复杂度。乍一想,找到每个节点的前驱节点的时间复杂度应该是 O ( n log n ) O(n\log n) ,因为找到一个节点的前驱节点和树的高度有关。 但事实上,找到所有节点的前驱节点只需要O(n) 时间。一棵 n 个节点的二叉树只有 n-1 条边,每条边只可能使用2次,一次是定位节点,一次是找前驱节点。 故复杂度为 O(n)。

空间复杂度:O(n)。使用了长度为 n 的数组。

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/er-cha-shu-de-zhong-xu-bian-li-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

感想

迭代通过栈来消除递归,这个知识点有点生疏了…… 写了好一会

执行用时 :2 ms, 在所有 Java 提交中击败了53.44%的用户

内存消耗 :34.2 MB, 在所有 Java 提交中击败了59.39%的用户

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        LinkedList<Integer> res = new LinkedList<>();
        TreeNode temp = root;
        while(temp!=null || !stack.isEmpty()){
            while(temp!=null) {
                stack.push(temp);
                temp=temp.left;
            }
            temp = stack.pop();
            res.add(temp.val);
            temp = temp.right;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/ZeromaXHe/article/details/92826895