[LeetCode] 94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Example 1:
Example 1
Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:
Input: root = []
Output: []

Example 3:
Input: root = [1]
Output: [1]

Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

Follow up: Recursive solution is trivial, could you do it iteratively?

二叉树的中序遍历。

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

思路

中序遍历我记为 左 - 根 - 右。
还是用GeeksforGeeks的例子来描述如何做中序遍历吧。

Tree Traversal

树的遍历大部分都是可以给出迭代和递归两种做法的,此题我也给出两种做法。两种做法的时间和空间复杂度一样,时间都是O(n),空间都是O(h)。

复杂度

时间O(n)
空间O(h)

迭代

迭代的做法需要用到一个栈。我们从根节点开始遍历,如果当前节点有左孩子,则把当前节点入栈的同时,一直往左子树走,这样我们能遍历到从根节点开始能走到的最深的左子树的叶子节点,这个节点也是中序遍历的结果的第一个。如果当前节点再没有左子树了,则把当前节点从栈弹出并记录到结果集的同时,往右子树走。这个遍历方式暗合了中序遍历的顺序,节点在从栈中被弹出的时候被加入结果集。

迭代代码

Java实现

/**
 * 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) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }
}

递归代码,很直白

Java实现

/**
 * 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) {
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }
}

关于为什么很多树的题目的空间复杂度是O(h) - 树的高度,我这里给一个discussion里面看到的截图。我看到这个截图我彻底懂了为什么是跟树的高度有关了。
Image

posted @ 2020-01-10 02:41  CNoodle  阅读(513)  评论(0编辑  收藏  举报