110.平衡二叉树
题目链接
判断一棵树是不是平衡二叉树
class Solution {
public:
bool blc(TreeNode *a,int &h){
if(a==NULL){h=0;return true;}
int hl,hr;
if(!blc(a->left,hl))return false;
if(!blc(a->right,hr))return false;
h = max(hl,hr) + 1;
if(abs(hl-hr)>1)return false;
return true;
}
bool isBalanced(TreeNode* root) {
int dep = 0;
return blc(root, dep);
}
};
112.路径总和
题目链接
判断是否存在一条从叶结点到根节点路径的权值和为sum
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)return false;
if(root->left==NULL && root->right == NULL && sum == root->val)return true;
if(hasPathSum(root->left,sum-root->val))return true;
if(hasPathSum(root->right,sum-root->val))return true;
return false;
}
};