首页 > 其他 > 详细

[GeeksForGeeks] Perfect Binary Tree

时间:2017-10-10 09:44:41      阅读:249      评论:0      收藏:0      [点我收藏+]

Given a Binary Tree, write a function to check whether the given Binary Tree is a prefect Binary Tree or not. A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level.

 

 1 class SubTreeInfo {
 2     boolean isPerfect;
 3     int height;
 4     SubTreeInfo(boolean isPerfect, int height) {
 5         this.isPerfect = isPerfect;
 6         this.height = height;
 7     }
 8 }
 9 public class PerfectBinaryTree {
10     public static boolean isPerfectBt(TreeNode root) {
11         return helper(root).isPerfect;
12     }
13     private static SubTreeInfo helper(TreeNode node) {
14         SubTreeInfo info = new SubTreeInfo(true, 0);
15         if(node == null) {
16             return info;
17         }
18         SubTreeInfo leftInfo = helper(node.left);
19         SubTreeInfo rightInfo = helper(node.right);
20         if(leftInfo.isPerfect && rightInfo.isPerfect && leftInfo.height == rightInfo.height) {
21             info.height = 1 + leftInfo.height;
22         }
23         else {
24             info.isPerfect = false;
25         }
26         return info;
27     }
28 }

 

[GeeksForGeeks] Perfect Binary Tree

原文:http://www.cnblogs.com/lz87/p/7643801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!