解題思路
由上往下一個個 node 去檢查
程式碼
class Solution {
public:
int getDepth(TreeNode* p)
{
if(p == nullptr)
return 0;
return max(getDepth(p->left), getDepth(p->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
int left = getDepth(root->left);
int right = getDepth(root->right);
if (abs(left - right) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
沒有留言:
張貼留言