[LeetCode]Balanced Binary Tree
来源:互联网 发布:js excel文件流下载 编辑:程序博客网 时间:2024/06/05 09:30
题目:
Balanced Binary Tree
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.
来源:https://oj.leetcode.com/problems/balanced-binary-tree/
思路:
判断二叉平衡树。
写一个BalancedHeight 函数用来计算某一节点的高度,然后对当前节点求其左右子树的高度差,最后递归检查其左右子树是否平衡。
C++ AC代码:
/** * Definition for binary tree * 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;if ( abs(BalancedHeight(root->left) - BalancedHeight(root->right)) > 1) return false;return isBalanced(root->left) && isBalanced(root->right); }int BalancedHeight (TreeNode* root){ if ( root == NULL ) return 0;int left = BalancedHeight (root->left);int right = BalancedHeight (root->right);return 1+max(left,right); }};
运行时间 60ms
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
- ##剑指offer 4.3 举例形象化问题2- 栈的压入和弹出序列
- 如何实现类似CAD的命令系统
- 双系统WIN7启动黑屏
- poj2028
- 【JAVA基础】⑤关于JAVA异常处理机制
- [LeetCode]Balanced Binary Tree
- 搭建阿里云服务器 配置命令 centos 5.8
- Java中的构造方法与普通方法的区别? 什么情况下用构造方法什么情况下用普通的方法
- git用法小结(1)--建立远程仓库
- Zookeeper--从0单排第二集 迅速开始
- verilog中assign语句
- 分拆素数和(2098)
- hdu oj1102 Constructing Roads(最小生成树)
- 国内IT行业的小企业发展所需要的是什么?