【LintCode-93】平衡二叉树(Java实现-递归算法)
来源:互联网 发布:曲面电视优缺点知乎 编辑:程序博客网 时间:2024/06/05 10:01
第一次代码记录:
public boolean isBalanced(TreeNode root) { if(root==null||(root.left==null&&root.right==null)){ return true; } if(root.left!=null&&root.right!=null){ return isBalanced(root.left)&&isBalanced(root.right); }else if(root.left!=null){ return depth(root.left)>1?false:true; }else{ return depth(root.right)>1?false:true; } // write your code here } public int depth(TreeNode root){ if(root==null){ return 0; } int leftRootDepth=depth(root.left); int rightRootDepth=depth(root.right); return (leftRootDepth>rightRootDepth?leftRootDepth:rightRootDepth)+1; }
LintCode测试BUG指出:
在LintCode提交测试,显示正常通过,但其实是不全对,因为代码里只判断了单独的左右子树是否平衡(return isBalanced(root.left)&&isBalanced(root.right);),而没有判断当前这个节点,左右子树的高度差是否满足小于等于1的平衡条件。测试数据:{1,2,3,4,5,#,#,6,7,8,9,#,#,#,#} 根节点左右子树不平衡。
第二次代码记录:
public boolean isBalanced(TreeNode root) { if(root==null){ return true; } int depthRootLeft=depth(root.left); int depthRootRight=depth(root.right); if(Math.abs(depthRootLeft-depthRootRight)<=1){ return isBalanced(root.left)&&isBalanced(root.right); } return false; } public int depth(TreeNode root){ if(root==null){ return 0; } int depthLeft=depth(root.left); int depthRight=depth(root.right); return (depthLeft>depthRight?depthLeft:depthRight)+1;//取左右子树最大值+1; }
个人解题思路:
判断当前这个二叉树是否平衡,其实就是判断这个二叉树上的没有treeNode节点是否平衡。
1.我们需要先求出这个左右子树的高度(通过depth()),depth()里用了递归算法求出其参数root节点的左右子树高度,并取其最大值+1。
2.回来isBalanced()里,取到左右子树高度后,进行判断当前节点是否平衡,如果平衡就继续递归其左右子树节点是否平衡,并将两者结果用且(&&)返回。
如果您有更好的解法,欢迎您在留言区补充,感谢!!
阅读全文
0 0
- 【LintCode-93】平衡二叉树(Java实现-递归算法)
- Lintcode-递归-93 平衡二叉树
- 【LintCode-66】二叉树的前序遍历(Java实现-递归算法/非递归算法)
- 【LintCode-67】二叉树的中序遍历(Java实现-递归算法/非递归算法)
- lintcode-平衡二叉树 -93
- LintCode 93-平衡二叉树
- 平衡二叉树(AVL树)算法 Java实现
- LintCode:平衡二叉树
- 平衡二叉树,lintcode
- lintcode平衡二叉树
- LintCode 平衡二叉树
- 平衡二叉树-LintCode
- lintcode--平衡二叉树
- 平衡二叉树-LintCode
- LintCode 平衡二叉树
- LintCode之93 平衡二叉树
- 平衡二叉树插入、删除(递归算法)
- 平衡二叉树插入、删除(非递归算法)
- Java.11.03
- MySQL——索引的使用对查询、插入速度的影响
- ABP官方文档(四十一)【ASP.NET Core】
- Leetcode 303
- Centos7 配置 JDK8
- 【LintCode-93】平衡二叉树(Java实现-递归算法)
- ABP官方文档(四十二)【CSRF和XSRF保护】
- [LeetCode] Maximum Subarray
- hadoop源码阅读之mapreduce再理解
- react native 的赋值比较,空字符串以及undefined
- memcpy(b,a,sizeof(a))
- Android 淡入淡出动画
- Java模拟鼠标键盘输入事件 --- Robot 类
- 判断是否能构成三角形并计算面积