List a Tree's Values Left, Node, Right
Solve this ProblemYou are given the root of a binary tree, where each node holds an integer val and has a left and a right child (either may be missing). Return the values of all nodes in the order you meet them when, at every node, you first walk the entire left subtree, then take the node itself, then walk the entire right subtree.
Writing this as a recursive helper is the direct approach. The same order can also be produced without recursion by keeping your own stack of the nodes that are still waiting for their turn.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ number of nodes ≤ 100 - ◆
−100 ≤ node.val ≤ 100 - ◆
The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child - ◆
Visit every node's left subtree first, then the node itself, then its right subtree, and return the values in the order visited
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Walk
GoodLet the call stack do the bookkeeping. A helper visits a node by first walking its entire left subtree, then recording the node's own value, then walking its right subtree. A missing child (null) simply returns. Every node is entered once, so the time is O(n); the recursion is as deep as the tree is tall, so the extra space is O(h) (up to O(n) for a tree that is a single long chain).
O(n)O(h)1class Solution {
2 public List<Integer> inorderValues(TreeNode root) {
3 List<Integer> out = new ArrayList<>();
4 walk(root, out);
5 return out;
6 }
7
8 private void walk(TreeNode node, List<Integer> out) {
9 if (node == null) return;
10 walk(node.left, out);
11 out.add(node.val);
12 walk(node.right, out);
13 }
14}Optimal — Iterative Walk With an Explicit Stack
OptimalReplace the call stack with a stack of your own. From the current node, keep going left, pushing every node passed on the way down. When there is nothing further left, pop the top node — that is the next value in order — record it, and move to its right child, then repeat the same walk down the left edge of that subtree. Stop when there is no current node and the stack is empty. Every node is pushed and popped exactly once (O(n) time), and the stack never holds more than one root-to-node path (O(h) space) — with no risk of overflowing the call stack on a very deep tree.
O(n)O(h)1class Solution {
2 public List<Integer> inorderValues(TreeNode root) {
3 List<Integer> out = new ArrayList<>();
4 Deque<TreeNode> stack = new ArrayDeque<>();
5 TreeNode cur = root;
6 while (cur != null || !stack.isEmpty()) {
7 while (cur != null) {
8 stack.push(cur);
9 cur = cur.left;
10 }
11 cur = stack.pop();
12 out.add(cur.val);
13 cur = cur.right;
14 }
15 return out;
16 }
17}