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

来源:互联网 发布:科比的技术特点知乎 编辑:程序博客网 时间:2024/05/17 22:57
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;    }}
原创粉丝点击