Balanced Binary Tree
来源:互联网 发布:手机文档解密软件 编辑:程序博客网 时间:2024/06/07 00:29
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,继续判断它的左子树和右子树是不是平衡二叉树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; int left=sub_height(root.left); int right=sub_height(root.right); int diff=Math.abs(left-right); if(diff>1) return false; else return isBalanced(root.left) && isBalanced(root.right); } public int sub_height(TreeNode subTree) { if(subTree==null) return 0; if(subTree.left==null && subTree.right==null) return 1; if(subTree.left==null) return sub_height(subTree.right)+1; if(subTree.right==null) return sub_height(subTree.left)+1; return Math.max(sub_height(subTree.right),sub_height(subTree.left))+1; }}
0 0
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- 慎用Outline ,UGUI Outline实现原理分析
- 380多个梦想的力量
- java http get、post方式
- Qt5.4连接MySql
- 13.1.6
- Balanced Binary Tree
- 建立一个堆结构heap-build
- cocos2d-x lua table与json的转换
- iOS UILabel自动换行,自适应高度
- cmake学习(一)静态库与动态库构建
- C语言字符串操作函数
- 每日一题G
- leetcode--Rotate Image
- HBase Coprocessor to Index Columns into ElasticSearch