猿问

打印从 Root 到每个叶子的所有路径

对于每个节点都具有以下元组的树:

(值,左节点,右节点)

如何打印从根到每个叶子的所有可能的价值链?

例如: (1,(2,(4,(7,None,None),None),(5, None, None)),(3,None,(6, None,None)))

它应该代表以下树:

预期结果是:
[1,2,4,7]
[1,2,5]
[1,3,6]

蝴蝶不菲
浏览 420回答 1
1回答

BIG阳

似乎您正在尝试解决此问题:https : //leetcode.com/problems/binary-tree-paths/在这里,您可以简单地开始使用 dfs 探索树并在树中向下存储值并维护从根到当前节点的所有值的向量。处理完该节点后,只需从该向量中删除当前节点处的值。当我们到达叶节点时,我们只需将向量中的值附加到我们的答案中。这是在 cpp 中实现的代码供您参考:/*** Definition for a binary tree node.* struct TreeNode {*&nbsp; &nbsp; &nbsp;int val;*&nbsp; &nbsp; &nbsp;TreeNode *left;*&nbsp; &nbsp; &nbsp;TreeNode *right;*&nbsp; &nbsp; &nbsp;TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/class Solution {&nbsp;public:&nbsp; &nbsp;void solve(TreeNode* root, vector<int>&values, vector<string>&ans) {&nbsp; &nbsp; if (root == NULL) return;&nbsp; &nbsp; if (root->left == NULL && root->right == NULL) {&nbsp; &nbsp; &nbsp; &nbsp; // leaf node&nbsp; &nbsp; &nbsp; &nbsp; string str = "";&nbsp; &nbsp; &nbsp; &nbsp; values.push_back(root->val);&nbsp; &nbsp; &nbsp; &nbsp; str += ::to_string(values[0]);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i < values.size(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str += "->";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str += ::to_string(values[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ans.push_back(str);&nbsp; &nbsp; &nbsp; &nbsp; values.pop_back();&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; &nbsp; values.push_back(root->val);&nbsp; &nbsp; solve(root->left, values, ans);&nbsp; &nbsp; solve(root->right, values, ans);&nbsp; &nbsp; values.pop_back();&nbsp; }&nbsp;vector<string> binaryTreePaths(TreeNode* root) {&nbsp; &nbsp; vector<int>values;&nbsp; &nbsp; vector<string>ans;&nbsp; &nbsp; solve(root,values,ans);&nbsp; &nbsp; return ans;&nbsp; }};
随时随地看视频慕课网APP

相关分类

Python
我要回答