inorder postorder traversal 对比

今天花了很久,比较了一下 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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值