剑指Offer打卡29 —— AcWing 72. 平衡二叉树
作者:互联网
【题目描述 】
【思路】
枚举每一个节点 判断该节点的左右子树高度是否相差1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int getDepth(TreeNode root){
if( root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
return left > right ? left + 1 : right + 1;
}
public boolean isBalanced(TreeNode root) {
if( root == null ) return true;
//获得以root为根的左右子树的高度
int left = getDepth(root.left);
int right = getDepth( root.right);
if( Math.abs(left - right) > 1 ) return false;
return isBalanced(root.left) && isBalanced(root.right);
}
}
标签:right,TreeNode,Offer,int,getDepth,二叉树,打卡,root,left 来源: https://blog.csdn.net/weixin_44855907/article/details/115269660