统计路径和等于一个数的路径数量
class Solution {
public:
int SumCount(TreeNode* root, int targetSum, bool takeroot){
int ans = 0;
if(root->val == targetSum)
ans += 1;
if(takeroot){
ans += root->left != NULL ? SumCount(root->left, targetSum - root->val, true) : 0;
ans += root->right != NULL ? SumCount(root->right, targetSum - root->val, true) : 0;
}
else{
ans += root->left != NULL ? SumCount(root->left, targetSum, false) : 0;
ans += root->right != NULL ? SumCount(root->right, targetSum, false) : 0;
ans += root->left != NULL ? SumCount(root->left, targetSum - root->val, true) : 0;
ans += root->right != NULL ? SumCount(root->right, targetSum - root->val, true) : 0;
}
return ans;
}
int pathSum_Recursive(TreeNode* root, int targetSum) {
if(root == NULL)
return 0;
return SumCount(root, targetSum, false);
int ans = 0;
void helper(TreeNode* root, vector<int>& path, int target){
if(root == NULL)
return ;
path.push_back(root->val);
int sum = 0;
for(int i = path.size()-1;i >= 0; i--){
sum += path[i];
if(sum == target)
ans += 1;
}
helper(root->left, path, target);
helper(root->right, path, target);
path.pop_back();
}
int pathSum(TreeNode* root, int targetSum){
if(root == NULL)
return 0;
vector<int> path;
ans = 0;
helper(root, path, targetSum);
return ans;
}
};
子树
class Solution {
public:
bool match(TreeNode* root, TreeNode* subRoot){
if(root == NULL && subRoot == NULL)
return true;
if(root == NULL || subRoot == NULL)
return false;
if(root->val == subRoot->val)
return match(root->left, subRoot->left) && match(root->right, subRoot->right);
else
return false;
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if(root == NULL)
return false;
if(match(root, subRoot))
return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
};
树的对称
class Solution {
public:
bool isSymmetricPair(TreeNode* node1, TreeNode* node2){
if(node1 == NULL && node2 == NULL)
return true;
if(node1 == NULL || node2 == NULL)
return false;
return node1->val == node2->val && isSymmetricPair(node1->left, node2->right) && isSymmetricPair(node1->right, node2->left);
}
bool isSymmetric(TreeNode* root) {
if(root == NULL)
return true;
return isSymmetricPair(root->left, root->right);
}
};
最小路径
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<pair<TreeNode*, int> > q;
q.push(make_pair(root, 1));
while(!q.empty()){
pair u = q.front();
q.pop();
TreeNode* node = u.first;
int depth = u.second;
if(node->left == NULL && node->right == NULL)
return depth;
else{
if(node->left != NULL)
q.push(make_pair(node->left, depth+1));
if(node->right != NULL)
q.push(make_pair(node->right, depth+1));
}
}
return 0;
}
};
统计左叶子节点的和
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
return sumHelper(root, false);
}
int sumHelper(TreeNode* node, bool isLeft){
if(node == NULL)
return 0;
if(node->left == NULL && node->right == NULL && isLeft)
return node->val;
return sumHelper(node->left, true) + sumHelper(node->right, false);
}
};