问题描述
题目看链接:https://leetcode.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;
if(Math.abs(maxDepth(root.left)-maxDepth(root.right))>1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
}
}
- 时间复杂度:O(2^n)
- 空间复杂度:O(1)