[程序员代码面试指南]二叉树问题-计算完全二叉树节点数

时间:2019-06-22 09:10:48   收藏:0   阅读:171

题意

计算完全二叉树节点数。

题解

代码

package Tree;

public class NodeCnt {
    public static void main(String args[]) {
        Node root=new Node(10);
        Node node1=new Node(11);
        Node node2=new Node(14);
        Node node3=new Node(11);
        Node node4=new Node(15);
        Node node5=new Node(16);
        root.left=node1;
        root.right=node2;
        node1.left=node3;
        node1.right=node4;
        node2.left=node5;
        
        System.out.print(nodeCnt(root));
    }
    public static int nodeCnt(Node root) {
        if(root==null) {
            return 0;
        }
        return search(root,1,mostLeftNodeH(root,1));
    }
    public static int search(Node root,int h,int H) {
        if(h==H) {
            return 1;
        }
        if(mostLeftNodeH(root.right,h+1)==H) {//
            return (1<<(H-h))+search(root.right,h+1,H);//
        }
        else {
            return (1<<(H-h-1))+search(root.left,h+1,H);
        }
    }
    public static int mostLeftNodeH(Node root,int level) {//从原始root
        Node node=root;
        while(node!=null) {
            ++level;
            node=node.left;
        }
        return level-1;//
    }
}

原文:https://www.cnblogs.com/coding-gaga/p/11067465.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!