leetcode -- Balanced Binary Tree TODO

时间:2022-02-01 08:29:49

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 everynode never differ by more than 1.

[解题思路]

检查每个node是否是balanced,大数据集挂掉了

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null){
return true;
} return checkBalance(root);
} public boolean checkBalance(TreeNode node){
if(node == null){
return true;
}
int left = getDepth(node.left);
int right = getDepth(node.right);
if(Math.abs(left - right) > 1){
return false;
}
return checkBalance(node.left) && checkBalance(node.right);
} public int getDepth(TreeNode node){
if(node == null){
return 0;
}
int left = getDepth(node.left);
int right = getDepth(node.right);
return Math.max(left, right) + 1;
}
}