平衡二叉树

特性:
它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树,同时,平衡二叉树必定是二叉搜索树,反之则不一定。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace BalanceTree
 8 {
 9     public class TreeNode
10     {
11         public int value;
12         public TreeNode left;
13         public TreeNode right;
14 
15         TreeNode(int x)
16         {
17             value = x;
18         }
19 
20     }
21 
22     class Program
23     {
24         public bool isBalance(TreeNode root)
25         {
26             if (GetHeight(root) == -1)
27             {
28                 return false;
29             }
30             return true;
31         }
32         public int GetHeight(TreeNode root)
33         {
34             if (root == null)
35             {
36                 return 0;
37             }
38             int leftHeight = GetHeight(root.left);
39             int rightHeight = GetHeight(root.right);
40 
41             if (leftHeight == -1 || rightHeight == -1)
42             {
43                 return -1;
44             }
45             if (Math.Abs(leftHeight - rightHeight) > 1)
46             {
47                 return -1;
48             }
49 
50             return Math.Max(leftHeight, rightHeight) + 1;
51         }
52 
53         static void Main(string[] args)
54         {
55            
56         }
57     }
58 }

 

posted @ 2017-11-02 17:15  美美美少女  阅读(191)  评论(0编辑  收藏  举报