94. Binary Tree Inorder Traversal - Easy

前往題目

想法

  • Recursion

思路

Recursive:

  1. 呼叫方法,並傳遞left
  2. 加入結果
  3. 呼叫方法,並傳遞right

Iterative:

  1. 迭代整個樹
  2. 嘗試走到最左邊,無法再走時加入其父節點到結果
  3. 把當前指針變為右邊繼續迭代

Code

Recursive

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

    private void inorder(TreeNode node) {
        if (node == null) return;

        inorder(node.left);
        res.add(node.val);
        inorder(node.right);
    }
}

Iterative

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList();
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;

        // Traverse the whole tree
        while (cur != null || !stack.isEmpty()) {
            // Go to the left whenever possible
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // Reach a null, pop the parent node
            cur = stack.pop();
            // Add to the result
            res.add(cur.val);
            // Go to the right
            cur = cur.right;
        }
        return res;
    }
}

94. Binary Tree Inorder Traversal - Easy
https://f88083.github.io/2024/10/16/94-Binary-Tree-Inorder-Traversal-Easy/
作者
Simon Lai
發布於
2024年10月16日
許可協議