二叉树递归求高度,非递归求高度,层次遍历

import java.util.LinkedList;
import java.util.Queue;

public class Main {
    //非递归求高度
    public static int bTNonRecursiveHeight(Node root){
        int front=-1,rear=-1;
        int level=0,last=0;
        Node[] queue=new Node[1000];
        if(root==null) return 0;
        queue[++rear]=root;
        while(front<rear){
            Node p=queue[++front];
            if(p.left!=null){
                queue[++rear]=p.left;
            }
            if(p.right!=null){
                queue[++rear]=p.right;
            }
            if(front==last){
                level++;
                last=rear;
            }
        }
        return level;
    }

    //递归求高度
    public static int bTRecursiveHeight(Node node){
        if(node==null) return 0;
        int leftdepth=bTRecursiveHeight(node.left);
        int rightdepth=bTRecursiveHeight(node.right);
        return leftdepth>rightdepth?leftdepth+1:rightdepth+1;
    }

    //层次遍历
    public static void levelTraversal(Node root){
        if(root==null) return;
        Queue<Node> queue=new LinkedList<Node>();
        queue.add(root);
        int level=0;
        int count=1;
        while(!queue.isEmpty()){
            Node n=queue.poll();
            System.out.print(n.data+" ");
            if(count==Math.pow(2,level)){
                level++;
                count=0;
                System.out.println();
            }
            if(n.left!=null){
                queue.add(n.left);
            }
            if(n.right!=null){
                queue.add(n.right);
            }
            count++;
        }
    }
    public static void main(String[] args) {
        Node root=new Node(10);
        Node a=new Node(4);
        Node b=new Node(20);
        Node c=new Node(3);
        Node d=new Node(5);
        Node e=new Node(15);
        Node f=new Node(25);
        root.left=a;
        root.right=b;
        a.left=c;
        a.right=d;
        b.left=e;
        b.right=f;
        System.out.println(bTNonRecursiveHeight(root));
        System.out.println(bTRecursiveHeight(root));
        levelTraversal(root);
    }
}

class Node{
    int data;
    Node left;
    Node right;
    public Node(int data){
        this.data=data;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值