94. Binary Tree Inorder Traversal

题目

输入输出

Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].

答案一

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<Integer>();

    Stack<TreeNode> stack = new Stack<TreeNode>();
    TreeNode cur = root;

    while(cur!=null || !stack.empty()){
        while(cur!=null){
            stack.add(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        list.add(cur.val);
        cur = cur.right;
    }

    return list;
}

图文详解

  • 深入左根
  • 从栈中 pop 并转向右子

参考

Iterative solution in Java - simple and readable

results matching ""

    No results matching ""