题目描述


题解
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;
preOrder(root.left);
if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) > 1)
res = false;
preOrder(root.right);
}
private int searchDepth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(searchDepth(root.left), searchDepth(root.right));
}
}
public class Solution {
public boolean res = true;
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null)
return res;
preOrder(root);
return res;
}
private void preOrder(TreeNode root) {
if (root == null)
return;
preOrder(root.left);
if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) > 1)
res = false;
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(searchDepth(root.left) - searchDepth(root.right)) <= 1) {
return isBalanced(root.left) && isBalanced(root.right);
}
else
return false;
}
private int searchDepth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(searchDepth(root.left), searchDepth(root.right));
}
}
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if (root == null)
return true;
if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) <= 1) {
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
else
return false;
}
private int searchDepth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(searchDepth(root.left), searchDepth(root.right));
}
}