Leetcode Balanced Binary Tree
2015-07-31 10:06
465 查看
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。这里用递归的方法来解决。
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。这里用递归的方法来解决。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if (root == NULL) return true; int depthleft = getdepth(root->left,1); int depthright = getdepth(root->right,1); if(abs(depthleft-depthright) > 1) { return false; } else { return isBalanced(root->left)&&isBalanced(root->right); } } int getdepth(TreeNode* root,int depth) { if(root==NULL) { return depth; } else { return max(getdepth(root->left,depth+1),getdepth(root->right,depth+1)); } } };
相关文章推荐
- 点修改区间查询 HDU1754
- PAT (Advanced Level) 1091. Acute Stroke (30) 3维DFS(10M数据时栈溢出)、3维BFS(AC)
- 字符串反转之——手摇算法
- hdu5328
- 【暑期基础】M HDU 2012 素数判定
- Let the Balloon Rise
- Wi-Fi 定位的原理
- Android ContentObserver 监听图库变化
- 读SAFEARRAY,内容是BSTR一维数组
- 暑假训练-个人赛第五场
- Trapping Rain Water
- 02_js中接口的定义和使用
- HDU 1829 A Bug's Life
- Spring_配置文件格式介绍--真的蛮详细
- HDU 5326 Work(求每个人的下属,直接和间接)
- Git使用总结(win7)
- 面向对象设计原则详解:单一职责原则
- tomcat
- 【暑期基础】L HDU 2011 多项式求和
- 【暑期基础】K HDU 2010 水仙花数