110. Balanced Binary Tree
Description
https://leetcode.com/problems/balanced-binary-tree/
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.
Solutions
没有思路,可以从定义来想:
balanced要求左子树和右子树的高度差<=1
,可以(先序)遍历结点,分别计算树高。
Submissions
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(maxDepth(root.left)-maxDepth(root.right))>1)
return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}
Summary
- 又是毫无思路,不知道要怎么判断,跑去问哥,哥说,就是每个
deep(parent)=max(deep(l),deep(r))
if(deep(l)–deep(r)绝对值>1) return false
就是后序遍历,先把左右儿子的深度算出来。
没有理解这个后序遍历是要怎样。 - 一开始写的时候没有写递归的调用
return isBalanced(root.left)&&isBalanced(root.right);
,写成了return true
,是没有理解递归吗。
直接return true
,就不会在往下检查左子树和右子树是否是平衡树了哦。所以要注意balanced BST的递归定义,每个子树都要是balanced BST才可以。