https://leetcode.com/problems/binary-tree-inorder-traversal
Description
Given the root
of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
**Input:** root = [1,null,2,3]
**Output:** [1,3,2]
Example 2:
**Input:** root = []
**Output:** []
Example 3:
**Input:** root = [1]
**Output:** [1]
Example 4:
**Input:** root = [1,2]
**Output:** [2,1]
Example 5:
**Input:** root = [1,null,2]
**Output:** [1,2]
Constraints:
The number of nodes in the tree is in the range [0, 100]
.
Follow up: Recursive solution is trivial, could you do it iteratively?
AC1: Divide and conquer
Like a queen, order two worker bee to report their result, and then combine her own with them.
/**
* 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<Integer>();
if (root == null) return res;
// Divide
List<Integer> left = new ArrayList<Integer>();
List<Integer> right = new ArrayList<Integer>();
// Conquer
res.addAll(left);
res.add(root.val);
res.addAll(right);
return res;
}
}
AC2: Traversal
Like a worker bee, traversal the tree and record in a note.
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
traversal(root, res);
return res;
}
private void traversal(TreeNode root, List<Integer> res) {
if (root == null) return;
traversal(root.left, res);
res.add(root.val);
traversal(root.right, res);
}
}
AC3: non-recursive
Use Stack to simulate recursion. In this way, it has higher memory capacity than system recursion.
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
// Variable
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
// Corner case
if (root == null) return res;
// Business
while (curr != null || !stack.empty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}