题目链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/
题目如下:
/**
* 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) {
dfs(root);
return res;
}
int dfs(TreeNode* root){
if(root==nullptr) return 0;
if(res==false) return 0;//用于提前终止递归
int left=dfs(root->left);
int right=dfs(root->right);
if(abs(left-right)>1) res=false;
return max(left,right)+1;
}
private:
bool res=true;
};