LeetCode || 平衡二叉树
程序员文章站
2022-02-19 06:33:36
...
平衡二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int right = 0;
int left = 0;
public boolean isBalanced(TreeNode root) {
if(root == null||(root.right==null&&root.left==null)){
return true;
}else if(Math.abs(right-left)>1){
return false;
}else{
right++;
left++;
isBalanced(root.left);
isBalanced(root.right);
}
return true;
}
}
正确的
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
if(Math.abs(Depth(root.left)-Depth(root.right))>1) return false;
else return isBalanced(root.left)&&isBalanced(root.right);
}
private int Depth(TreeNode root){//求深度
if(root==null) return 0;
return Math.max(Depth(root.left),Depth(root.right))+1;
}
}