larscheng / algo

0 stars 0 forks source link

【Check 45】2024-04-07 - 94. 二叉树的中序遍历 #147

Open larscheng opened 6 months ago

larscheng commented 6 months ago

94. 二叉树的中序遍历

larscheng commented 6 months ago

思路

class Solution { //O(n)/O(n) //递归中序遍历 public List inorderTraversal(TreeNode root) { List res = new ArrayList<>(); inorder(root, res); return res; }

private void inorder(TreeNode root, List<Integer> res) {
    if (root == null) {
        return;
    }
    inorder(root.left, res);
    res.add(root.val);
    inorder(root.right, res);
}

}

```java
    //左节点+根节点+右节点
    //addall 空间复杂度高O(n^2)
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        res.addAll(inorderTraversal(root.left));
        res.add(root.val);
        res.addAll(inorderTraversal(root.right));
        return res;
    }

复杂度

larscheng commented 6 months ago

思路

复杂度

larscheng commented 6 months ago

思路

这种栈结构中,最先出栈的必定是左子树,最先记录的节点必定是左叶子节点

代码

class Solution {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Stack<Object> stack = new Stack<>();
        if (root==null){
            return res;
        }
        stack.push("white");
        stack.push(root);

        while (!stack.isEmpty()){
            TreeNode node = (TreeNode) stack.pop();
            String color = (String) stack.pop();
            if (node == null){
                continue;
            }
            if (color.equals("white")){
                stack.push("white");
                stack.push(node.right);
                stack.push("gray");
                stack.push(node);
                stack.push("white");
                stack.push(node.left);
            }else {
                res.add(node.val);
            }
        }
        return res;
    }

}

复杂度