Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
题意:中序遍历二叉树
题解:用递归的方法很容易求解,但是对于大部分计算机而言,递归比循环慢得多,所以这里给出一种运用栈的方法。
Solution1: recrusion
public class Solution {
private List<Integer> list=new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root!=null)
{
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
}
return list;
}
}
Solution2:Stack&&Iteration
public class Solution {
private List<Integer> list=new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
TreeNode x=root;
Stack<TreeNode>s=new Stack<TreeNode>();
while(x!=null||!s.isEmpty())
{
while(x!=null)
{
s.push(x);
x=x.left;
}
x=s.peek();
s.pop();
list.add(x.val);
x=x.right;
}
return list;
}
}