标签:tmp 面试 wrapper 遇到 数据 desc ram core dump 提交
原题网址:https://www.lintcode.com/problem/binary-tree-path-sum/description
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值
的路径。
一个有效的路径,指的是从根节点到叶节点的路径。
给定一个二叉树,和 目标值 = 5
:
1
/ 2 4
/ 2 3
返回:
[
[1, 2, 2],
[1, 4]
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode * root, int target) {
// write your code here
vector<vector<int>> result;
if (root==NULL)
{
return result;
}
vector<int> tmp;
int sum=0;
trav(result,tmp,root,target,sum);
return result;
}
void trav(vector<vector<int>> &result,vector<int> &tmp, TreeNode * root, int target, int & sum)
{
tmp.push_back(root->val);
sum+=root->val;
if (root->left==NULL&&root->right==NULL)
{
if (sum==target)
{
result.push_back(tmp);
}
return ;
}
if (root->left!=NULL)
{
trav(result,tmp,root->left,target,sum);
sum=sum-root->left->val;
tmp.pop_back();
}
if (root->right!=NULL)
{
trav(result,tmp,root->right,target,sum);
sum=sum-root->right->val;
tmp.pop_back();
}
}
};
标签:tmp 面试 wrapper 遇到 数据 desc ram core dump 提交
原文地址:https://www.cnblogs.com/Tang-tangt/p/9198391.html