中序遍历二叉树的非递归的两种实现、线序遍历统计二叉树的叶子数、二叉树的深度

在此内容之上增加了中序遍历二叉树的非递归的两种实现、线序遍历统计二叉树的叶子数、二叉树的深度

//中序遍历二叉树非递归
    public void InOrderTraverse(BinaryNode<T> node){
        Stack<BinaryNode> stack=new Stack<BinaryNode>();
        if(node!=null)
            stack.add(node);
        while(!stack.isEmpty()){
            while(stack.peek()!=null){
                node=stack.peek().left;
                stack.push(node);
            }
            stack.pop();
            if(!stack.isEmpty()){
                node=stack.pop();
                System.out.print(node.data+" ");
                stack.push(node.right);
            }
        }
    }
    //中序遍历二叉树非递归
    public void InOrderTraverse2(BinaryNode<T> node){
        Stack<BinaryNode> stack=new Stack<BinaryNode>();
        BinaryNode<T> p=node;
        while(p!=null || !stack.isEmpty()){
            if(p!=null){
                p=stack.push(p);
                p=p.left;
            }else{
                p=stack.pop();
                System.out.print(p.data+" ");
                p=p.right;
            }
        }
    }
    int count=0;
    //先序遍历统计二叉树中的叶子节点
    public int countLeaf(BinaryNode<T> node){
        if(node!=null){
            if(node.left==null&&node.right==null)
                count++;
            countLeaf(node.left);
            countLeaf(node.right);
        }
        return count;
    }
    //统计二叉树的深度
    public int treeDepth(BinaryNode<T> node){
        int depthral=0;
        int depthLeft=0;
        int depthRight=0;
        if(node==null)
            depthral=0;
        else{
            depthLeft=treeDepth(node.left);
            depthRight=treeDepth(node.right);
            depthral=1+(depthLeft>depthRight? depthLeft:depthRight);
        }
        return depthral;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值