Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
遍历大家知道分为前序,中序,后序(不知道的同学请看这里http://baike.baidu.com/view/1455143.htm)
树的题都是非常有技巧性的,所以这道题的核心思想是:中序的顺序+stack栈
1.stack push进root结点
2.如果有left,把left变成root,但返回1;
3.如果没有left,把right变成root,返回1;
这样一看是不是简单多了?!
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class BinaryTreeInorderTraversal {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> tree = new ArrayList<Integer>();
if(root==null) return tree;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p=root;
while(!stack.empty()||p!=null){
if(p!=null) {
stack.push(p);
p=p.left;
}
else{
tree.add(stack.pop().val);
p=stack.pop().right;
}
}
return tree;
}
}