已知一棵完全二叉树,求其节点的个数 要求:时间复杂度低于O(N),N为这棵树的节点个数

 1 package my_basic.class_4;
 2 
 3 public class Code_08_CBTNode {
 4     // 完全二叉树的节点个数 复杂度低于O(N)
 5 
 6     public static class Node {
 7         int value;
 8         Node left;
 9         Node right;
10 
11         public Node(int value) {
12             this.value = value;
13         };
14     }
15 
16     public static int nodeNum(Node head) {
17         if (head == null) {
18             return 0;
19         }
20         return bs(head, 1, mostLeftLevel(head, 1));
21     }
22 
23     public static int bs(Node node, int level, int h) {
24         if (level == h) {
25             return 1;
26         }
27         if (mostLeftLevel(node.right, level + 1) == h) {
28             System.out.println("递归中右 = h --:"+(1 << (h - level) + bs(node.right, level + 1, h)));
29             return (1 << (h - level)) + bs(node.right, level + 1, h);
30         } else {
31             System.out.println("递归中右 != h:"+(1 << (h - level - 1) + bs(node.left, level + 1, h)));
32             return (1 << (h - level - 1)) + bs(node.left, level + 1, h);
33         }
34     }
35 
36     public static int mostLeftLevel(Node node, int level) {
37         while (node != null) {
38             level++;
39             node = node.left;
40         }
41         return level - 1;
42     }
43     
44     //打印二叉树
45     public static void printTree(Node head) {
46         System.out.println("Binary Tree:");
47         printInOrder(head, 0, "H", 17);
48         System.out.println();
49     }
50 
51     public static void printInOrder(Node head, int height, String to, int len) {
52         if (head == null) {
53             return;
54         }
55         printInOrder(head.right, height + 1, "v", len);
56         String val = to + head.value + to;
57         int lenM = val.length();
58         int lenL = (len - lenM) / 2;
59         int lenR = len - lenM - lenL;
60         val = getSpace(lenL) + val + getSpace(lenR);
61         System.out.println(getSpace(height * len) + val);
62         printInOrder(head.left, height + 1, "^", len);
63     }
64 
65     public static String getSpace(int num) {
66         String space = " ";
67         StringBuffer buf = new StringBuffer("");
68         for (int i = 0; i < num; i++) {
69             buf.append(space);
70         }
71         return buf.toString();
72     }
73 
74     
75     public static void main(String[] args) {
76         Node head = new Node(1);
77         head.left = new Node(2);
78         head.right = new Node(3);
79         head.left.left = new Node(4);
80         head.left.right = new Node(5);
81         head.right.left = new Node(6);
82         System.out.println(nodeNum(head));
83         
84 //        printTree(head);
85 
86     }
87 }

原文地址:https://www.cnblogs.com/lihuazhu/p/10963885.html