Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
[1,null,2,3]
,1 \ 2 / 3
return
[1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
Solution:
While we have not finish traversing the tree, we do:
1. Push the current one and go left and push the current one until we cannot go left anymore.
2. Pop one node and add it to the result.
3. If we can go right, go right.
Code:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); result.add(root.val); root = root.right; } return result; } }