/**
* 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:
bool hasPathSum(TreeNode* root, int sum) {
return is_sum(root,sum);
}
bool is_sum(TreeNode * root,int sum){
if(root == NULL){
return false;
}
if(!root->right && !root->left){
if(sum == root->val){
return true;
}
}
return (is_sum(root->left,sum-root->val) || is_sum(root->right,sum-root->val));
}
};
思路:递归判断root的子树和是否等于sum-root->val
Leetcode113.路径总和II
/**
* 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<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> vec;
vector<int> v;
is_sum(vec,v,root,sum);
return vec;
}
void is_sum(vector<vector<int>> &vec,vector<int> v, TreeNode *root,int sum){ //注意此处的v没有引用
if(root == nullptr) return;
v.push_back(root->val);
if(root->val == sum && root->left == nullptr && root->right == nullptr ){
vec.push_back(v);
}
is_sum(vec,v,root->left,sum-root->val);
is_sum(vec,v,root->right,sum-root->val);
}
};
**思路:**因为要存储相加等于sum的节点的值所以使用vector<vector>类型容器存储,当存在和为sum的节点时,先存到vector v中,再讲vector v存到vector<vector>。注意:,vector v 并不使用引用,有回溯过程。
Leetcode 94.二叉树的中序遍历
/**
* 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> vec;
vector<int> inorderTraversal(TreeNode* root) {
inorder_binary(root);
return vec;
}
void inorder_binary(TreeNode * root){
if(root == nullptr) return ;
inorderTraversal(root->left);
vec.push_back(root->val);
inorderTraversal(root->right);
}
};