二叉树的深度和平衡二叉树
来源:互联网 发布:舞蹈扇子淘宝网 编辑:程序博客网 时间:2024/09/21 06:36
求平衡二叉树二叉树要用到二叉树的深度,所以将这两个算法放在一起。
首先来看球二叉树的深度。
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路比较简单,就是递归比较左右子树的高度值,取较大的值。
//二叉数的数据结构public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}public int TreeDepth(TreeNode pRoot){ if(pRoot == null) return 0; return Math.max(TreeDepth(pRoot.left)+1, TreeDepth(pRoot.right)+1);}
接下来看看判断一棵二叉树是不是平衡二叉树。
平衡二叉树具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
//二叉数的数据结构public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}public boolean IsBalanced_Solution(TreeNode root) { if(root == null) return true; if (Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) return false; return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);}public int getHeight(TreeNode pRoot){ if(pRoot == null) return 0; return Math.max(getHeight(pRoot.left)+1, getHeight(pRoot.right)+1);}
1 0
- 二叉树的深度和平衡二叉树
- 二叉树的深度,平衡二叉树深度
- 求二叉树的深度和宽度平衡最大距离
- 二叉树的深度求值和判断是否是平衡
- 二叉树深度和判断平衡二叉树
- 平衡二叉树(二叉树深度+DFS)
- 二叉树深度、平衡二叉树的判断
- 【笔试】50、二叉树的深度&&判断平衡二叉树
- 二叉树的深度以及判断平衡二叉树
- 二叉树的深度及平衡二叉树40
- 剑指Offer: 二叉树的深度、平衡二叉树
- 二叉树的深度,判断是否是平衡二叉树
- 剑指Offer 39 二叉树的深度+平衡二叉树
- 二叉树的深度以及判断平衡二叉树
- 39 二叉树的深度和宽度以及判断是否是平衡二叉树
- 剑指offer 39. 二叉树的深度和判断是否为平衡二叉树
- 平衡二叉树的
- 二叉树的深度,平衡二叉树,二叉树的镜像
- 柴俊理金:油价美股支撑风险,避险黄金遭受打压
- 文章标题
- LeetCode 339. Nested List Weight Sum
- mysql的一些注意的
- MySQL事务管理+安全管理+MySQL数据类型
- 二叉树的深度和平衡二叉树
- 屏幕触摸
- 关于统计变换(CT/MCT/RMCT)算法的学习和实现
- java之斐波拉契问题(生兔子)
- 缓存穿透、缓存并发、缓存失效之思路变迁
- android5.0效果的下拉刷新、上拉加载,可滚动置顶
- iOS开发之多语言
- win7安装SQL Server2008时,用户权限设置问题导致安装失败
- CoreData 数据库更新,数据迁移