剑指offer:判定平衡二叉树
来源:互联网 发布:淘宝几块一只的人参 编辑:程序博客网 时间:2024/05/16 17:24
平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。这个方案很好的解决了二叉查找树退化成链表的问题,把插入,查找,删除的时间复杂度最好情况和最坏情况都维持在O(logN)。但是频繁旋转会使插入和删除牺牲掉O(logN)左右的时间,不过相对二叉查找树来说,时间上稳定了很多。
题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
总的想法: //判断根节点左右子树的深度,高度差超过1,则不平衡
方法一:
class Solution {public: bool IsBalanced_Solution(TreeNode* pRoot,int &depth){ if(pRoot==NULL){ depth=0; return true; } int ld,rd; bool l=IsBalanced_Solution(pRoot->left,ld); bool r=IsBalanced_Solution(pRoot->right,rd); depth=1+max(ld,rd); if(l&&r&&(ld>rd?ld-rd:rd-ld)<=1) return true; else return false; } bool IsBalanced_Solution(TreeNode* pRoot) { int depth; return IsBalanced_Solution(pRoot,depth); }};
方法二:(单独的函数求节点深度)
public class Solution { //判断根节点左右子树的深度,高度差超过1,则不平衡 public boolean IsBalanced_Solution(TreeNode root) { if (root==null) { return true; } int left = getTreeDepth(root.left); int right = getTreeDepth(root.right); return (left-right)>1?false:true; } //求取节点的深度 public static int getTreeDepth(TreeNode root) { if (root==null) { return 0; } int leftDepth = 1+getTreeDepth(root.left); int rightDepth = 1+getTreeDepth(root.right); return leftDepth>rightDepth?leftDepth:rightDepth; }}
更多文章:http://my.csdn.net/wodeqingtian1234
阅读全文
0 0
- 剑指offer:判定平衡二叉树
- 12.剑指offer-平衡二叉树的判定
- 码农小汪剑指Offer之37-平衡二叉树判定
- 平衡二叉树判定
- 平衡二叉树判定
- 剑指offer--平衡二叉树
- 《剑指offer》平衡二叉树
- 剑指Offer--平衡二叉树
- 剑指offer-平衡二叉树
- 剑指offer:平衡二叉树
- 剑指offer 平衡二叉树
- 剑指offer:平衡二叉树
- [剑指offer]平衡二叉树
- 剑指offer|平衡二叉树
- 《剑指offer》-平衡二叉树
- 剑指offer-平衡二叉树
- 剑指offer: 平衡二叉树
- 剑指offer:平衡二叉树
- [paper] Meta-Learner LSTM
- mysql主主复制(双主复制)配置步骤
- linux 网卡bond
- html和xml的区别
- 汇编语言 实验10.1 显示字符串
- 剑指offer:判定平衡二叉树
- 【Spring 数据访问终篇】Spring + Hibernate + Mysql
- 【CountDownLatch】实现多个线程同时启动
- OpenGL ES零基础入门四矩形的绘制
- bzoj 1022
- Python 实践心得 —— 中英混杂的字符串对齐输出
- Unity中的持久化数据PlayerPrefs
- 学生学籍管理系统~~功能界面
- Spring 自动依赖注入