Balanced Binary Tree -- leetcode
来源:互联网 发布:淘宝网1元秒杀专区 编辑:程序博客网 时间:2024/06/06 06:42
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.
引入一辅助函数,其返回树的深度。
同时,如果其发现自己左右子树已经不平稀,则返回-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) { return helper(root) != -1; } int helper(TreeNode *root) { if (!root) return 0; const int left = helper(root->left); if (left == -1) return left; const int right = helper(root->right); if (right == -1 || abs(left-right)>1) return -1; return max(left, right) + 1; }};
0 0
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode-Balanced Binary Tree
- LeetCode - Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- LeetCode | Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- 最大子段和
- OC知识总结(一)
- Factory Method模式的误区:Factory Method模式是简化版的Abstract Factory吗?
- ZigZag Conversion
- vs2012下mfc程序通过ado方式使用access数据库编译的程序在xp底下无法使用解决方法
- Balanced Binary Tree -- leetcode
- 神经网络与机器学习笔记——贝叶斯分类器
- 高通平台 lcd driver 调试小结
- [Practical.Vim(2012.9)].Drew.Neil.Tip04学习摘要
- Android图片处理(Matrix,ColorMatrix)
- Android_shape详解
- 黑马程序员----[20150509][IO流3]
- 黑马程序员IOS-OC语言-Foundation-结构体
- Builder模式的误区:将复杂对象的构建进行封装,就是Builder模式了吗?