题目
思路 自顶向下
从根节点开始,计算左右子树的高度,看看满不满足<=1的条件。
递归的思想还需要再练练!
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int calDepth(TreeNode* root){
if(root==nullptr) return 0;
return max(calDepth(root->left),calDepth(root->right))+1;
}
bool isBalanced(TreeNode* root) {
if(root==nullptr) return true;
return abs(calDepth(root->left)-calDepth(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
};
思路 自底向上
这个方法比较难想。后序遍历,从叶节点开始,如果满足平衡子树就计算当前节点的高度,如果不满足就返回-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:
int recur(TreeNode* root){
if(root==NULL) return 0;
int left=recur(root->left);
if(left==-1) return -1;
int right=recur(root->right);
if(right==-1) return -1;
return abs(left-right)<=1?max(left,right)+1:-1;
}
bool isBalanced(TreeNode* root) {
return recur(root)!=-1;
}
};