平衡二叉树

https://leetcode-cn.com/problems/balanced-binary-tree/
代码如下
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int depthLeft = maxDepth(root.left);
int depthRight = maxDepth(root.right);
if (Math.abs(depthLeft - depthRight) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {
return true;
} else {
return false;
}
}
public int maxDepth (TreeNode root) {
if (root == null) return 0;
else {
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
}
网友评论