L94. Binary Tree Inorder Traversal
Binary tree: in order(left root right)
Problem:
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
Solution:
recursion
private List<Integer> res;
public List<Integer> inOrder(TreeNode root){
res = new ArrayList<>();
helper(root);
return res;
}
private void helper(TreeNode root){
if(root == null) return;
helper(root.left);
res.add(root.val);
helper(root.right);
}
iteration
public List<Integer> inOrder(TreeNode root){
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.isEmpty()){
if(root == null){
root = stack.pop();
res.add(root.val);
root = root.right;
}else{
stack.push(root);
root = root.left;
}
}
return res;
}
Last updated
Was this helpful?