时间复杂度比较高的一种写法,但是思路能想到,就是一层一层判断当前节点是否平衡。题解称之为先序遍历
/**
* 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 l,r;
l = dfs(root.left);
r = dfs(root.right);
return Math.abs(l-r)<=1&&isBalanced(root.left) && isBalanced(root.right);
}
public int dfs(TreeNode root){
if(root == null) return 0;
return Math.max(dfs(root.left),dfs(root.right)) + 1;
}
}
学习一下后序遍历的写法
/**
* 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) {
return dfs(root) != -1;
}
public int dfs(TreeNode root){
if(root == null) return 0;
int left = dfs(root.left);
if(left == -1) return -1;
int right = dfs(root.right);
if(right == -1) return -1;
return Math.abs(left-right) < 2 ? Math.max(left,right)+1:-1;
}
}