144. Binary Tree Preorder Traversal - Easy

前往題目

想法

  • Inorder那題大同小異,加入結果的位置調換一下就好

思路

Recursive:

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

Iterative:

  1. 迭代整個樹
  2. 嘗試走到最左邊,期間遇到節點就加入(他們都是父節點)
  3. 把當前指針變為右邊繼續迭代

Code

Recursive

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

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

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

Iterative

class Solution {
    public List<Integer> preorderTraversal(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) {
                res.add(cur.val); // Add the parent node
                stack.push(cur); // Memorize the parent node
                cur = cur.left; // Move to the deeper left
            }
            // Reach the null, pop the parent
            cur = stack.pop();
            // Go to the right
            cur = cur.right;
        }
        return res;
    }
}

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