题目描述

题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val
* TreeNode left
* TreeNode right
* TreeNode() {}
* TreeNode(int val) { this.val = val
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val
* this.left = left
* this.right = right
* }
* }
*/
// 本题和【剑指offer】55.2 平衡二叉树 一模一样
//
// 执行用时:88 ms, 在所有 Java 提交中击败了5.18%的用户
// 内存消耗:39.1 MB, 在所有 Java 提交中击败了5.07%的用户
class Solution {
public boolean res = true
public boolean isBalanced(TreeNode root) {
if (root == null)
return res
preOrder(root)
return res
}
private void preOrder(TreeNode root) {
if (root == null)
return
if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) > 1)
res = false
preOrder(root.left)
preOrder(root.right)
}
private int searchDepth(TreeNode root) {
if (root == null)
return 0
return 1 + Math.max(searchDepth(root.left), searchDepth(root.right))
}
}
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
if (Math.abs(depth(root.left) - depth(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public int depth(TreeNode root) {
if (root == null)
return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}