Skip to content

94. Binary Tree Inorder Traversal

Linjie Pan edited this page Jun 27, 2019 · 1 revision

This is an iterative solution for tree inorder traversal. The key of the solution lies in:

  1. Use current to denote the node under process;
  2. Use stack to save nodes;
  3. A node is added to the result list iff it is popped out of the stack
public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> resultList = new ArrayList<Integer>();
    Stack<TreeNode> stack = new Stack<TreeNode>();
	TreeNode current = root; 
    while (current != null || !stack.isEmpty()) {
        while (current != null) { 
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        resultList.add(current.val);
        current = current.right;
    }
    return resultList;
}
Clone this wiki locally