To prove safety offer 39. balanced binary tree
topic
Input binary tree, the binary tree is determined whether a balanced binary tree.
Thinking
Lazy continued, with a code of a preceding question, seeking depth, compare left and right subtrees depth before returning, if the difference is greater than 1, the result is set to false.
Code
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
boolean ans = true;
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if (Math.abs(left - right) > 1) {
ans = false;
}
return Math.max(left, right) + 1;
}
public boolean IsBalanced_Solution(TreeNode root) {
int i = TreeDepth(root);
return ans;
}