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 1: Recursive Approach
We can define a helper function inOrder to handle recursion.
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inOrder(res, root);
return res;
}
private void inOrder(List<Integer> res, TreeNode root) {
if (root == null) {
return;
}
inOrder(res, root.left);
res.add(root.val);
inOrder(res, root.right);
}
Time Complexity: T(n) = 2T(n/2) + 1. According to Master Method, time complexity is O(n)
Space Complexity: O(n)
Solution 2: Iterating Approach by Using Stack
Same idea with recursion approach, just implement it with stack.
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
Time Complexity: O(n)
Space Complexity: O(n)