[leetcode] 110. Balanced Binary Tree
来源:互联网 发布:c4d r16 mac安装 编辑:程序博客网 时间:2024/05/22 05:02
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.
这道题是判断二叉树是否是平衡二叉树,题目难度为Easy。
根据平衡二叉树的定义,只需要借助求二叉树深度的函数即可通过递归来判断二叉树是否平衡,而二叉树深度又可以通过深度优先的方法递归得到。具体代码:
class Solution { int depth(TreeNode* n) { if(!n) return 0; return max(depth(n->left), depth(n->right)) + 1; }public: bool isBalanced(TreeNode* root) { if(!root) return true; return isBalanced(root->left) && isBalanced(root->right) && abs(depth(root->left)-depth(root->right))<=1; }};上面代码中自顶向下来求二叉树深度,在递归过程中靠下的节点会多次计算其深度。还可以通过自底向上的方法来计算深度,节点深度通过两个子节点深度来计算,这样就避免了对节点的多次遍历,每个节点只遍历一次,时间复杂度从O(nlogn)降到了O(n),具体代码:
class Solution { int depth(TreeNode* n) { if(!n) return 0; int lDepth = depth(n->left); if(lDepth == -1) return -1; int rDepth = depth(n->right); if(rDepth == -1) return -1; if(abs(lDepth-rDepth) > 1) return -1; return max(lDepth, rDepth) + 1; }public: bool isBalanced(TreeNode* root) { return depth(root) != -1; }};
0 0
- LeetCode 110. Balanced Binary Tree
- [LeetCode]110.Balanced Binary Tree
- 【LeetCode】110.Balanced Binary Tree
- [Leetcode] 110. Balanced Binary Tree
- LeetCode --- 110. Balanced Binary Tree
- [leetcode] 110.Balanced Binary Tree
- [leetcode]110. Balanced Binary Tree
- LeetCode:110. Balanced Binary Tree
- 110. Balanced Binary Tree LeetCode
- [LeetCode]110. Balanced Binary Tree
- Leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- LeetCode *** 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- #leetcode#110. Balanced Binary Tree
- leetcode-110. Balanced Binary Tree
- POJ 1961 字符串 KMP (i-next[i])
- poj 3169 差分约束
- php从mysql取出int数据,变成了string
- Effetive Objective - C 1.Objective 23.委托与数据源协议进行对象间通信
- Android总结篇系列:Android广播机制
- [leetcode] 110. Balanced Binary Tree
- Oracle中有关Group by 中avg();sum();min();max();count();的运用整理(Oracle的执行顺序)
- 阿里2017校园招聘电话面试总结
- 数据挖掘的一些评价标准
- xshell传输文件
- POJ3308
- C语言实现 螺旋数 方阵
- HDU 4857 逃生 (拓扑排序+反向建图)
- mysql的外键