1. 程式人生 > 其它 >LeetCode94.二叉樹的中序遍歷(迭代法)

LeetCode94.二叉樹的中序遍歷(迭代法)

技術標籤:LeetCodeleetcode

給定一個二叉樹的根節點 root ,返回它的中序遍歷
示例 1:
在這裡插入圖片描述

輸入:root = [1,null,2,3]
輸出:[1,3,2]

示例2:

輸入:root = []
輸出:[]

示例 3:

輸入:root = [1]
輸出:[1]

Java 解題程式碼

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        
        Deque<TreeNode> stack = new LinkedList
<>(); ArrayList<Integer> array = new ArrayList<>(); // 根節點為空,直接返回 if (root == null) { return array; } TreeNode cur = root; while (cur != null || !stack.isEmpty()) { if (cur != null) { // 當前節點不為空時,將當前節點的左子節點加入到棧中,便於後續訪問
stack.push(cur); cur = cur.left; } else { // 當前節點為空時,就從棧中彈出一個節點,取出值放到array中,並右子節點設定為當前節點 cur = stack.pop(); array.add(cur.val); cur = cur.right; } } return array; }
}