Leetcode 94. Binary Tree Inorder Traversal
Description:
For example:
Given binary tree [1,null,2,3]
.
1
\
2
/
3
return [1,3,2]
.
Thinking:
Nothing special except we should change the order of that we add root.val
to the List
.
Steps:
- Check if the current node is empty / null
- Recursion or iteration?
- Do we need create helper function?
- How to recursion? Traverse the left subtree by recursively calling the in-order function. Display the data part of the root (or current node). Then traverse the right subtree by recursively calling the in-order function.
- Determin the
return
condition.
Code:
Iteration:
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return new ArrayList<Integer>();
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while(!stack.isEmpty() || current != null){
while(current != null){
stack.push(current);
current = current.left;
}
current = stack.pop();
result.add(current.val);
current = current.right;
}
return result;
}
}
Recursion(with helper):
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorderTraversalhelper(root,result);
return result;
}
private void inorderTraversalhelper(TreeNode root,List<Integer> result){
if(root == null) return;
inorderTraversalhelper(root.left, result);
result.add(root.val);
inorderTraversalhelper(root.right,result);
}
}
Recuraion(no helper):
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return new ArrayList<Integer>();
List<Integer> result = new ArrayList<Integer>();
List<Integer> left = inorderTraversal(root.left);
List<Integer> right = inorderTraversal(root.right);
result.addAll(left);
result.add(root.val);
result.addAll(right);
return result;
}
}
Conclusion:
recursion(no helper) is a little bit slower than with helper, since result.addAll()
takes O(n).