From : https://leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root, int& dep) {
if(!root) {dep=0; return true;}
int left, right;
if(isBalanced(root->left, left) && isBalanced(root->right, right)) {
if(abs(right-left) <= 1) {
dep = 1+max(left, right);
return true;
}
}
return false;
}
bool isBalanced(TreeNode *root) {
int dep;
return isBalanced(root, dep);
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private static class Depth {
int v = 0;
}
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return isBalanced(root, new Depth());
}
// dep is the deep of root
boolean isBalanced(TreeNode root, Depth dep) {
if (root == null) {
dep.v = 0;
return true;
}
Depth left = new Depth(), right = new Depth();
if (isBalanced(root.left, left) && isBalanced(root.right, right)) {
if (Math.abs(right.v - left.v) <= 1) {
dep.v = 1 + Math.max(right.v, left.v);
return true;
}
}
return false;
}
}