构造树:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x;}
}
递归:
public class Solution {
List<Integer> result = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root !=null){
helper(root);
}
return result;
}
public void helper(TreeNode p){
if(p.left!=null)
helper(p.left);
result.add(p.val);
if(p.right!=null)
helper(p.right);
}
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root==null)
return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode top = stack.peek();
if(top.left!=null){
stack.push(top.left);
top.left=null;
}else{
result.add(top.val);
stack.pop();
if(top.right!=null){
stack.push(top.right);
}
}
}
return result;
}