LeetCode OJ 110. Balanced Binary Tree

时间:2023-03-09 13:29:37
LeetCode OJ 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。如果超过1,那么该树也是不平衡的。如何记录节点的深度呢,我们可以利用节点中的val来存储一个节点和它的子树组成的树的深度。是不是很巧妙呢?代码如下:

 /**
* 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;
if(root.left == null && root.right == null){
root.val = 1;
return true;
} int leftdeep = 0;
int rightdeep = 0;
if(root.left != null){
if(!isBalanced(root.left)) return false;
leftdeep = root.left.val;
}
if(root.right != null){
if(!isBalanced(root.right)) return false;
rightdeep = root.right.val;
} if(Math.abs(leftdeep - rightdeep) > 1) return false;
root.val = leftdeep>rightdeep?leftdeep+1:rightdeep+1;
return true;
}
}