94. Binary Tree Inorder Traversal

1. iterative

่‹ฅ cur ไธ็‚บ null

ไธ€่ทฏ่ตฐๅทฆ, ๆ›ดๆ–ฐ cur ็‚บๅทฆ

ๅˆฐๅบ•ไบ† => pop(), ๅกžๅ€ผ,

ๆชขๆŸฅๅณ้‚Šๆœ‰็„กๅ…ƒ็ด 

ๆœ‰: ๅˆไธ€่ทฏ่ตฐๅทฆ

็„ก: pop() ๅกžๅ€ผ

ๅ่ฆ†...

O(n), O(n)


class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        
        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;
    }
}

or like this

ๅชๆœ‰ๅค–้ขๆœ‰ while, ๅฅฝๅƒๆฏ”่ผƒๅˆ็†, ๆฆ‚ๅฟตไธ€ๆจฃ

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

}

2. recursion

ๆ™‚้–“่ค‡้›œๅบฆ๏ผšO ๏ผˆn ๏ผ‰ใ€‚

็ฉบ้–“่ค‡้›œๅบฆ๏ผšๆœ€ๅฃžๆƒ…ๆณไธ‹้œ€่ฆ็ฉบ้–“ไธŠO ๏ผˆn ๏ผ‰๏ผŒๅนณๅ‡ๆƒ…ๆณ็‚บO๏ผˆ log n๏ผ‰ใ€‚

this is more clean

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        helper(root, res);
        return res;
    }
    private void helper (TreeNode root, List<Integer> res) {
        if (root == null) return;
        helper(root.left, res);
        res.add(root.val);
        helper(root.right, res);
    }
}

Last updated