题目
统计完全二叉树的节点数
java代码
package com.lizhouwei.chapter3;
/**
* @Description:统计完全二叉树的节点数
* @Author: lizhouwei
* @CreateDate: 2018/4/16 21:47
* @Modify by:
* @ModifyDate:
*/
public class Chapter3_24 {
public int nodeNum(Node head) {
if (head == null) {
return 0;
}
return bs(head, 1, getLevel(head, 1));
}
private int bs(Node head, int level, int h) {
if (level == h) {
return 1;
}
if (getLevel(head.right, level + 1) == h) {
return (1 << (h - level)) + bs(head.right, level + 1, h);
} else {
return (1 << (h - level - 1)) + bs(head.left, level + 1, h);
}
}
private int getLevel(Node head, int level) {
while (head != null) {
level++;
head = head.left;
}
return level - 1;
}
//测试
public static void main(String[] args) {
Chapter3_24 chapter = new Chapter3_24();
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(7);
head.left.left = new Node(2);
head.left.right = new Node(4);
head.right.left = new Node(6);
head.right.right = new Node(8);
head.left.left.left = new Node(1);
System.out.print("中序数组:");
NodeUtil.inOrder(head);
System.out.print("节点个数:" + chapter.nodeNum(head));
}
}
结果
![](https://images2018.cnblogs.com/blog/1369004/201804/1369004-20180416221617978-1624316659.png)