Implement an iterative, in-order traversal of a given binary tree, return the list of keys of each node in the tree as it is in-order traversed.
Examples
5
/ \
3 8
/ \ \
1 4 11
In-order traversal is [1, 3, 4, 5, 8, 11]
Corner Cases
What if the given binary tree is null? Return an empty list in this case.
iterative:
1 public List<Integer> inOrder(TreeNode root) { 2 // Write your solution here 3 List<Integer> res = new ArrayList<>() ; 4 Deque<TreeNode> stack = new LinkedList<>() ; 5 //helper is the one-step ahead for the root 6 TreeNode helper = root ; 7 while(helper != null || !stack.isEmpty()){ 8 if (helper != null) { 9 stack.offerFirst(helper); 10 helper = helper.left ; 11 } else{ 12 TreeNode curr = stack.pollFirst(); 13 res.add(curr.key) ; 14 helper = curr.right ; 15 } 16 } 17 return res ; 18 }
recursive:
1 private List<Integer> preOrder_iter(TreeNode root){ 2 List<Integer> res = new ArrayList<>() ; 3 if (root == null) { 4 return res ; 5 } 6 helper(root, res); 7 return res ; 8 } 9 private void helper(TreeNode root , List<Integer> res ){ 10 //base case 11 if (root == null) { 12 return ; 13 } 14 helper(root.left, res) ; 15 res.add(root.key) ; 16 helper(root.right, res); 17 }