day17
我的问题:
写递归函数的时候,先去思考终止条件。而是先向每一层的递归逻辑。
同时,这里求的是高度,所以参数应该是根节点,而不是左右孩子。左右孩子应该将结果返还给根节点。所以是后序遍历。
写递归的时候,不要陷入到整个是怎样的。要去向一层是怎样完成的,不然很容易晕。想好一层之后,每一层都是一样的
class Solution {
public:
int compare(TreeNode* root)
{
int res = 0;
if(root == nullptr) return 0;
int leftHeight = compare(root->left);
if(leftHeight == -1) return -1;
int rightHeight = compare(root->right);
if(rightHeight == -1) return -1;
if(abs(leftHeight - rightHeight) > 1)
res = -1;
else
res = 1 + max(leftHeight,rightHeight);
return res;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
int res = compare(root);
if(res == -1) return false;
return true;
}
};