leetcode8.binaryTree后续遍历

问题不描述了,后续遍历二叉树,递归方法同leetcode7.(改下顺序)

非递归方法

package leetcode6and7.BinaryTree;

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public ArrayList<Integer>  postorderTraversal(TreeNode root){    
        
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        
        if(root == null)
            return arrayList;
            
        Stack<TreeNode>stack = new Stack<TreeNode>();
        stack.push(root);
        
        TreeNode prenote=null;
        while(!stack.empty()){
            
            TreeNode current = stack.peek();//look at the top of the stack,not rm it!
            //以下为仅有根节点,或者父节点第一次入栈
            if(prenote==null||prenote.left==current||prenote.right==current){//prenote==null then just root;
                if(current.left !=null){
                    stack.push(current.left);
                }else if(current.right!=null){
                    stack.push(current.right);
                }else{
                    stack.pop();
                    arrayList.add(current.val);
                }
            }else if(current.left==prenote){//此时第二次遍历到父节点,判断右子树是否有值,有值入栈,无值返回父节点
                if(current.right!=null){
                    stack.push(current.right);
                }else{
                    stack.pop();
                    arrayList.add(current.val);
                }
            }else if(current.right == prenote){//右子树已处理,处理父节点
                stack.pop();
                arrayList.add(current.val);
            }
            
            prenote=current;
            
        }//while
        
        return arrayList;
    }
}

总结:上学那会就很头疼这个,还是要回头多想多思考该方法

总体思路:首先考虑特殊情况,即只有一个根节点的情况,即prenote==null时的情况,接下去考虑正常情况,先向左子树遍历,遍历到最左下的节点,判断其是否有右子树,如有则入栈继续判断,如无则退栈保存当前最左下节点,处理完该节点,返回该节点(记为A)的父节点,此时A的父节点第二次被处理,判断其是否有右子树,即重复上述过程。

注意的是父节点会被俩次处理

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值