[LeetCode] 94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
[1,null,2,3]
,1 \ 2 / 3
return
[1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
Thought process:
Inorder traversal visits a tree in the order of left subtree - root - right subtree.
Solution 1 (Recursive):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> inorder = new ArrayList<>(); inorderTraversal(root, inorder); return inorder; } private void inorderTraversal(TreeNode root, List<Integer> inorder) { if (root == null) { return; } inorderTraversal(root.left, inorder); inorder.add(root.val); inorderTraversal(root.right, inorder); } } |
Time complexity: O(n).
The recursive solution is trivial. To solve this iteratively, we need to use a stack to simulate the function call stack. To achieve inorder traversal, we go to the left subtree until the leaf, and add nodes along the way.
Solution 2 (Iterative):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> inorder = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); inorder.add(root.val); root = root.right; } return inorder; } } |
Time complexity: O(n).
Comments
Post a Comment