leetcode - 110. Balanced Binary Tree
2018-01-29 22:16
183 查看
Problem:
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.
Example 1:
Given the following tree
Return true.
Example 2:
Given the following tree
Return false.
解释:判断给定的树是不是平衡二叉树。平衡二叉树是指每个结点左右两个子树的高度差绝对值不超过1,
例如Example 2中结点1左子树深度为3,右子树深度为1,相差超过1,就不是平衡二叉树了。
Solve:
就是求结点深度再判断的思想,调用递归解决,
①。求左结点深度,
②。求右结点深度,
③。左右比较,绝对值大于1的话返回-1;(结点深度不会是-1,所以-1是对非平衡的标识)
(时间复杂度O(n),AC-1ms)
后记:这道题开始想着是求根结点最大深度 然后求最小深度,两个绝对值大于1判断为非平衡树的,后来发现概念错了,
是对每个结点而言的,其实弄清概念很重要,再者代码根据求解树深度算法进行改造,理解了的话也不是很难。
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.
Example 1:
Given the following tree
[3,9,20,null,null,15,7]:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree
[1,2,2,3,3,null,null,4,4]:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
解释:判断给定的树是不是平衡二叉树。平衡二叉树是指每个结点左右两个子树的高度差绝对值不超过1,
例如Example 2中结点1左子树深度为3,右子树深度为1,相差超过1,就不是平衡二叉树了。
Solve:
就是求结点深度再判断的思想,调用递归解决,
①。求左结点深度,
②。求右结点深度,
③。左右比较,绝对值大于1的话返回-1;(结点深度不会是-1,所以-1是对非平衡的标识)
(时间复杂度O(n),AC-1ms)
public boolean isBalanced(TreeNode root) { if(getMaxDepth(root)==-1){ return false; } return true; } public static int getMaxDepth(TreeNode root) { if (root == null){ return 0; } else { int left = getMaxDepth(root.left);//左结点深度 int right = getMaxDepth(root.right);//右结点深度 if(left==-1||right==-1) return -1; if(left-right>1||right-left>1){//非平衡返回-1 return -1; } return 1 + Math.max(left, right);//求最大深度 } }
后记:这道题开始想着是求根结点最大深度 然后求最小深度,两个绝对值大于1判断为非平衡树的,后来发现概念错了,
是对每个结点而言的,其实弄清概念很重要,再者代码根据求解树深度算法进行改造,理解了的话也不是很难。
相关文章推荐
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- 【LeetCode】110. Balanced Binary Tree
- Leetcode-110. Balanced Binary Tree
- LeetCode110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree(平衡二叉树)
- LeetCode 110.Balanced Binary Tree
- [LeetCode] 110. Balanced Binary Tree 平衡二叉树
- LeetCode110.Balanced Binary Tree题解
- Leetcode 110. Balanced Binary Tree (Easy) (cpp)
- LeetCode 110. Balanced Binary Tree (平衡二叉树)
- [LeetCode]110. Balanced Binary Tree
- 110.[Leetcode]Balanced Binary Tree
- leetcode 110. Balanced Binary Tree-平衡二叉树|深度遍历
- LeetCode解题报告 110. Balanced Binary Tree
- leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法
- LeetCode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- 【Leetcode】110. Balanced Binary Tree
- LeetCode --- 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree