平衡二叉树
特性:
它是一棵空树或它的左右两个子树的高度差的绝对值不超过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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步