Problem
Given a binary tree, return the inorder traversal of its nodes' values.
Example
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,3,2]
.
Challenge
Can you do it without recursion?
Note
递归法不说了,栈迭代的helper
函数是利用stack
的LIFO原理,从根节点到最底层的左子树,依次push
入堆栈。然后将pop
出的结点值存入数组,并对pop
出的结点的右子树用helper
函数继续迭代。
Solution
Recursion
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList();
if (root == null) return res;
helper(root, res);
return res;
}
public void helper(TreeNode root, ArrayList<Integer> res) {
if (root.left != null) helper(root.left, res);
res.add(root.val);
if (root.right != null) helper(root.right, res);
}
}
Stack Iteration
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList();
Stack<TreeNode> stack = new Stack();
if (root == null) return res;
helper(stack, root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) helper(stack, cur.right);
}
return res;
}
public void helper(Stack<TreeNode> stack, TreeNode root) {
stack.push(root);
while (root.left != null) {
root = root.left;
stack.push(root);
}
}
}
Another Stack Iteration
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。