Balanced Binary Tree——数是否是平衡,即任意节点左右字数高度差不超过1
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode *root) { 13 if(root==NULL) return true; 14 int l=height(root->left); 15 int r=height(root->right); 16 if(l<0||r<0||l-r>1||r-l>1) return false; 17 return true; 18 } 19 int height(TreeNode *root){ 20 if(root==NULL) return 0; 21 int l=height(root->left); 22 int r=height(root->right); 23 if(l<0||r<0||l-r>1||r-l>1) return -1; 24 return max(l,r)+1; 25 } 26 };
其他做法:
转自:http://blog.csdn.net/feliciafay/article/details/18348065
1 // 68ms过大集合 简洁版 2 public: 3 int cntHeight(TreeNode *root) { 4 if(root == NULL) return 0; 5 int l = cntHeight(root->left); 6 int r = cntHeight(root->right); 7 if(l < 0 || r < 0 || abs(l-r) > 1) return -1; //自定义 return -1,表示不平衡的情况 8 else return max(l, r) + 1; 9 } 10 bool isBalanced(TreeNode *root) { 11 if(root == NULL) return true; 12 int l = cntHeight(root->left); 13 int r = cntHeight(root->right); 14 if(l < 0 || r < 0 || abs(l-r) > 1) return false; 15 else return true; 16 }
1 // 68ms过大集合 更简洁版 2 public: 3 int cntHeight(TreeNode *root) { 4 if(root == NULL) return 0; 5 int l = cntHeight(root->left); 6 int r = cntHeight(root->right); 7 if(l < 0 || r < 0 || abs(l-r) > 1) return -1; //自定义 return -1,表示不平衡的情况 8 else return max(l, r) + 1; 9 } 10 bool isBalanced(TreeNode *root) { 11 if(root == NULL) return true; 12 int l = cntHeight(root->left); 13 int r = cntHeight(root->right); 14 if(l < 0 || r < 0 || abs(l-r) > 1) return false; 15 else return true; 16 }
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了