今天花了很久,比较了一下 inorder 和 postorder traversal 的特点比较,
inorder :
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack=new Stack<TreeNode>();
ArrayList<Integer> list=new ArrayList<Integer>();
TreeNode current=root;
// take this into consideration: root--right
// and we need to check right and push right into stack when you go to the right tree
while(current!=null || !stack.isEmpty())
{ // go to the most left node if we have left node ,if we go to loop
if(current!=null)
{stack.push(current);
current=current.left;}
// if we don't have left node then we pop and go to the right tree, else we do process
else
{
current=stack.peek();
stack.pop();
list.add(new Integer(current.val));
current=current.right;
}
}
return list;
}
}
要注意到的地方是 while的判断你条件, 需要current ! =null 是因为,我们需要在visit 根节点的但是栈空得时候 将右边的tree 入栈, 所以判断条件一定得有
而postorder 相当于用一个output 栈来反序, 因为入栈的时候是 根,左-右的顺序,调整过后是 左-右,上一层 到根的顺序。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// solution idea usgin two stacks, the second one is to reverse the visiting output
// we change the root right left order into left -right-root order then out put
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
Stack<TreeNode> output = new Stack<TreeNode>();
TreeNode current=root;
if(root==null)return list;
stack.push(current);
while (!stack.isEmpty()){
current=stack.pop();
// if we have left child we put it into the stack
if(current.left!=null)stack.push(current.left);
// if we have right child we put it into the stack
if(current.right!=null)stack.push(current.right);
// then we put the current node into the output stack
output.push(current);
}
while(!output.isEmpty()){
list.add(output.pop().val);
}
return list;
}
}