[LeetCode] 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.
This question has been sorted out before. I will not elaborate on it here. I will paste the Code directly:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool fun(TreeNode* root,int& depth){ if(root==NULL){ depth=0; return true; } int left,right; if(fun(root->left,left)&&fun(root->right,right)){ int diff=left-right; if(abs(diff)<=1){ depth=1+(left>right?left:right); return true; } } return false; } bool isBalanced(TreeNode *root) { int depth=0; return fun(root,depth); }};
The following is the previous link: Balance Binary Tree judgment