LeetCode 110 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.
题意:
判断一颗二叉树是否是平衡二叉树,平衡二叉树的定义为,每个节点的左右子树深度相差小于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.
Solution 1:
这是和求最大深度的结合在一起,可以考虑写个helper函数找到拿到左右子树的深度,然后递归调用isBalanced函数判断左右子树是否也是平衡的,得到最终的结果。时间复杂度O(n^2)
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int leftDep = depthHelper(root.left);
int rightDep = depthHelper(root.right);
if (Math.abs(leftDep - rightDep) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {
return true;
}
return false;
}
private int depthHelper(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(depthHelper(root.left), depthHelper(root.right)) + 1;
}
Solution 2:
解题思路:
再来看个O(n)的递归解法,相比上面的方法要更巧妙。二叉树的深度如果左右相差大于1,则我们在递归的helper函数中直接return -1,那么我们在递归的过程中得到左子树的深度,如果=-1,就说明二叉树不平衡,也得到右子树的深度,如果=-1,也说明不平衡,如果左右子树之差大于1,返回-1,如果都是valid,则每层都以最深的子树深度+1返回深度。
public boolean isBalanced(TreeNode root) {
return dfsHeight(root) != -1;
}
//helper function, get the height
public int dfsHeight(TreeNode root){
if (root == null) {
return 0;
}
int leftHeight = dfsHeight(root.left);
if (leftHeight == -1) {
return -1;
}
int rightHeight = dfsHeight(root.right);
if (rightHeight == -1) {
return -1;
}
if (Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。