110. Balanced Binary Tree (Tree; DFS)
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.
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isBalanced(TreeNode *root) { if(!root) return true; flag = true; dfs(root,1); return flag; } int dfs(TreeNode* node, int depth){ if(!flag) { return 0; } if(!node->left && !node->right) { return depth; } int left=depth; int right=depth; if(node->left) { left = dfs(node->left,depth+1); } if(node->right) { right = dfs(node->right,depth+1); } if(abs(left-right)> 1) { flag = false; } return max(left,right); } private: bool flag; };