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?
M1: recursive
time: O(n), space: O(height)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) { return res; } inorder(root, res); return res; } public void inorder(TreeNode node, List<Integer> res) { if(node == null) { return; } inorder(node.left, res); res.add(node.val); inorder(node.right, res); } }
M2: iterative
time: O(n), space: O(n) -- worst case
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) { return res; } LinkedList<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; while(cur != null || !stack.isEmpty()) { while(cur != null) { stack.offerFirst(cur); cur = cur.left; } cur = stack.pollFirst(); res.add(cur.val); cur = cur.right; } return res; } }