平衡二叉树
来源:互联网 发布:淘宝dw全屏代码怎么用 编辑:程序博客网 时间:2024/06/07 11:27
问题描述:
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
解题思路:
首先考虑空二叉树或只有一个节点的时候,这种情况是平衡树,当存在左右子树时,要按定义来判断,判断是否存在以子树为根的二叉树,若有,则不是,否则,则是;然后,进行递归调用判断。
代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
if(root==NULL) return true;
if(root->left==NULL&&root->right!=NULL){
TreeNode *p=root->right;
if(p->left||p->right!=NULL) return false;
else return true;}
if(root->right==NULL&&root->left!=NULL){
TreeNode *q=root->left;
if(q->left||q->right!=NULL) return false;
else return true;
}
else{
return isBalanced(root->left)&&isBalanced(root->right);
}
// write your code here
}
};
开始没有按照平衡树的定义来处理
- 平衡二叉树平衡法则
- 二叉树--二叉平衡树
- 平衡二叉树的
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉查找树
- 平衡二叉树 详解
- 平衡二叉树
- 平衡二叉树
- AVL 平衡二叉树
- 平衡二叉树
- 平衡二叉树-红黑树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- 平衡二叉树
- [机器学习](六)cs229之EM算法
- 【Swift】14.0扩展
- 24点游戏是经典的纸牌益智游戏(Android版)
- c/c++
- day14-jdbc案例(简单的curd&分页)
- 平衡二叉树
- windows如何关闭和启动mysql
- Android 内存优化
- Delphi中ClientDataSet的用法小结
- 路由器和交换的区别解析
- 动态规划--滑雪
- HDU
- linux系统配置文件
- zoj 3870 异或运算