标签:null def 所有路径 vector targe 整数 int back tree node
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void pathSum(TreeNode* root, int target, std::vector<int>& tmp) { if (root == NULL) { return; } int val = root->val; int t1 = target - val; tmp.push_back(val); if (t1 == 0) { if (!root->left && !root->right) { res.push_back(tmp); } } pathSum(root->left, t1, tmp); pathSum(root->right, t1, tmp); tmp.erase(tmp.end() - 1); // 删除最末尾元素,这样形参可以传递引用,减少内存开销 } vector<vector<int>> pathSum(TreeNode* root, int target) { std::vector<int> tmp; pathSum(root, target, tmp); return res; } std::vector<std::vector<int>> res; };
标签:null def 所有路径 vector targe 整数 int back tree node
原文地址:https://www.cnblogs.com/morningsunlll/p/14587133.html