判断一棵二叉树是否是平衡二叉树

 1 package my_basic.class_4;
 2 
 3 public class Code_06_IsBalanceTree {
 4     //判断一颗树是否是平衡二叉树
 5     public static class Node{
 6         int value;
 7         Node left;
 8         Node right;
 9         public Node(int value) {
10             this.value = value;
11         }
12     }
13     
14     public static class ReturnData{
15         boolean isB;
16         int h;
17         public ReturnData(boolean isB, int h) {
18             this.isB = isB;
19             this.h = h;
20         }
21     }
22     public static boolean isBlanceTree(Node head) {
23         return process(head).isB;
24     }
25     
26     public static ReturnData process(Node head) {
27         if (head == null) {
28             return new ReturnData(true, 0);
29         }
30         ReturnData leftdata = process(head.left);
31         if (!leftdata.isB) {
32             return new ReturnData(false, 0);
33         }
34         ReturnData rightdata = process(head.right);
35         if (!rightdata.isB) {
36             return new ReturnData(false, 0);
37         }
38         if (Math.abs(leftdata.h - rightdata.h) > 1) {
39             return new ReturnData(false, 0);
40         }
41         return new ReturnData(true, Math.max(leftdata.h, rightdata.h) + 1);
42         
43     }
44     
45     //for test
46     public static void main(String[] args) {
47         Node head = new Node(1);
48         head.left = new Node(2);
49         head.right = new Node(3);
50         head.left.left = new Node(4);
51         head.left.right = new Node(5);
52         head.right.left = new Node(6);
53 //        head.right.right = new Node(7);
54         head.right.left.left = new Node(7);
55 
56         System.out.println(isBlanceTree(head));
57     }
58 }

 

posted @ 2019-06-02 18:51  _luckyz  阅读(567)  评论(0编辑  收藏  举报