Q:输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
T:
主要逻辑通过DFS函数递归实现,如果我的root节点不是叶子节点,用expectNumber-root->val就是root这一层向下的所有层的期待值,等到递归到了叶子节点,expcetNumber已经减掉了该叶子节点的所有祖先节点的值,那么这个叶子节点的val如果等于剩余的期待值就是符合题意的路径。
这里的vector
题目中有两个点:一是路径要到根节点;二是题目中有提,在返回值的list中,数组长度大的数组靠前,需要用sort排序。
P.S.实际上我觉得把allPath和path写在class中function外比较好。
vector<vector<int> > FindPath(TreeNode *root, int expectNumber) {
vector<vector<int> > allPath;
vector<int> path;
if (root)
DFS(root, expectNumber, allPath, path);
stable_sort(allPath.begin(), allPath.end(), [](const vector<int>& a, const vector<int>& b) { return a.size() > b.size();});
return allPath;
}
static void DFS(TreeNode *root, int sum, vector<vector<int> > &allPath, vector<int> &path) {
path.push_back(root->val);
if(!root->left&&!root->right) {
if (root->val == sum)
allPath.push_back(path);
}
if (root->left)
DFS(root->left, sum - root->val, allPath, path);
if (root->right)
DFS(root->right, sum - root->val, allPath, path);
path.pop_back();
}
原文:https://www.cnblogs.com/xym4869/p/12290468.html