LeetCode 110. Balanced Binary Tree
2016-04-17 08:49
267 查看
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 ofevery node never differ by more than 1.
Just follow the definition.....
For a better performance. It is good to build a data structure. To traversal the tree in bottom up order which might help to end the program earlier once detected unbalanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.
Just follow the definition.....
static int getDepth(TreeNode* root) { if(!root) return 0; return 1 + max(getDepth(root->left), getDepth(root->right)); } bool isBalanced(TreeNode* root) { if(!root) return true; int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); return abs(leftDepth - rightDepth) <= 1 && isBalanced(root->right) && isBalanced(root->left); }
For a better performance. It is good to build a data structure. To traversal the tree in bottom up order which might help to end the program earlier once detected unbalanced.
/* Build a structure */ class BalanceStatsWithHeight { bool balanced; int height; } BalanceStatsWithHeight checkBalanceTree(TreeNode* root) { if(!root) return {true, -1}; auto left_tree = checkBalanceTree(root->left); if(!left_tree.balanced) return {false, 0}; auto right_tree = checkBalanceTree(root->right); if(!right_tree.balanced) return {false, 0}; bool is_balance = abs(left_tree.height - right_tree.height) <= 1; int curr_height = max(left_tree.height, right_tree.height) + 1; return {is_balance, curr_height}; }
相关文章推荐
- Exposure Mask of Digital Cameras
- ASP.NET MVC下基于异常处理的完整解决方案
- 机器码和字节码
- MySQL本地可以连接,远程连接不上的问题
- 基于javascript实现图片切换效果
- kafaka参考链接
- 并行文件系统 BeeGFS 现已开源
- Redis源码剖析系列文章汇总
- 梦断代码阅读笔记01
- 大二上学期分班前的总结(上了快一年半大学的感悟)
- Android-简单适配器SimpleAdapter的用法
- 数据库索引
- LeetCode——036
- SQL 语句执行成本
- spring + myBatis 常见错误:SQL语法错误
- spring与mybatis整合
- 当对手有 45 亿资金、1 亿用户,你怎么办?
- AOP实践--ASP.NET MVC 5使用Filter过滤Action参数防止sql注入,让你代码安全简洁
- 非常棒的jQuery图片轮播效果
- 致佳音: 推箱子游戏自己主动求解算法设计(一)