437. Path Sum III
题目描述
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
代码实现
其实这道题目就是在之前的target sum的基础上做了一个延伸,需要把每个节点再作为起始节点计算target sum。另外一个就是不需要到达leaf就可以作为一个target sum。
/**
* 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:
void countTargetSumNumber(TreeNode *root, int sum, int &res) {
if(!root)
return;
sum -= root->val;
if(sum == 0)
res++;
if(root->left) countTargetSumNumber(root->left, sum, res);
if(root->right) countTargetSumNumber(root->right, sum, res);
}
int pathSum(TreeNode* root, int sum) {
stack<TreeNode*> stk; TreeNode* tp = NULL;
if(root) stk.push(root);
int res = 0;
while(!stk.empty()) {
tp = stk.top();
stk.pop();
int tmp = 0;
countTargetSumNumber(tp, sum, tmp);
if(tp->left) stk.push(tp->left);
if(tp->right) stk.push(tp->right);
res += tmp;
}
return res;
}
};
515. Find Largest Value in Each Tree Row
题目描述
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
代码实现
使用的BFS实现这道题目。
/**
* 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:
vector<int> largestValues(TreeNode* root) {
vector<int> res; TreeNode* tmp;
queue<TreeNode*> que;
if(root) que.push(root);
while(!que.empty()) {
int max = INT_MIN, sz = que.size();
while(sz--) {
tmp = que.front();
que.pop();
if(tmp->val > max)
max = tmp->val;
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
}
res.push_back(max);
}
return res;
}
};