2014.1.8 04:09
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.
Solution:
Just do as the problem says, calculate the heights and check if they meet the requirement.
Time complexity is O(n), where n is the number of nodes in the tree. Space complexity is O(1).
Accepted code:
1 // 1AC, good~ 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 bool isBalanced(TreeNode *root) { 14 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 if(root == nullptr){ 17 return true; 18 } 19 20 return myabs(treeHeight(root->left) - treeHeight(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); 21 } 22 private: 23 const int &myabs(const int &num) { 24 return (num >= 0 ? num : -num); 25 } 26 27 const int &mymax(const int &x, const int &y) { 28 return (x > y ? x : y); 29 } 30 31 int treeHeight(TreeNode *root) { 32 if(root == nullptr){ 33 return 0; 34 }else{ 35 return mymax(treeHeight(root->left), treeHeight(root->right)) + 1; 36 } 37 } 38 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)