码迷,mamicode.com
首页 > 其他好文 > 详细

[GeeksForGeeks] Perfect Binary Tree

时间:2017-10-10 09:57:35      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:des   whether   cti   tin   bool   static   geeks   btree   nod   

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

标签:des   whether   cti   tin   bool   static   geeks   btree   nod   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!