110. Balanced Binary Tree
来源:互联网 发布:淘宝卖aj鞋子的好店 编辑:程序博客网 时间:2024/06/18 06:27
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,则return false,否则继续递归下去
代码如下:
/** * 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: int height(TreeNode *root){ if(root==NULL)return 0; else{ int l=height(root->left); int r=height(root->right); return 1+((l>r)?l:r); } } bool isBalanced(TreeNode* root) { if(root==NULL)return true; else{ int l,r; l=height(root->left); r=height(root->right); if(l>r+1||r>l+1){ return false; } else{ return isBalanced(root->left)&&isBalanced(root->right); } } }};
阅读全文
0 0
- 110.Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 110. Balanced Binary Tree
- 2.5 利用matlab计算DFT
- 欢迎使用CSDN-markdown编辑器
- 枚举
- 个人博客开通!——Django从入门到...WordPress
- SQL 连续任意区间段分组统计
- 110. Balanced Binary Tree
- 2017年IT行业最赚钱的5个职位
- 在html中加入图片 url路径 要注意分号使用
- Jpa使用说明
- C语言作业-4-1素数和
- 不同路径下加载资源
- 整数中1出现的次数(从1到n整数中1出现的次数)
- 利用FFmpeg玩转Android视频录制与压缩(二)
- 3.1 FFT概述