对于其中每个节点都具有以下元组的树:
(值,LeftNode,RightNode)
如何打印从根到每个叶子的所有价值链?
例如: (1,(2,(4,(7,无,无),无),(5,无,无)),(3,无,(6,无,无)))
它应该代表以下树:
预期结果是:
[1,2,4,7]
[1,2,5]
[1,3,6]
答案 0 :(得分:2)
似乎您正在尝试解决此问题:https://leetcode.com/problems/binary-tree-paths/
在这里,您可以简单地开始使用dfs探索树并在树中下降时存储值,并维护从根到当前节点的所有值的向量。处理完该节点后,只需从该向量中删除当前节点上的值即可。当我们到达叶子节点时,我们只需将vector中的值附加到答案中即可。
以下是在cpp中实现的代码供您参考:
/**
* 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:
void solve(TreeNode* root, vector<int>&values, vector<string>&ans) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
// leaf node
string str = "";
values.push_back(root->val);
str += ::to_string(values[0]);
for (int i = 1; i < values.size(); ++i) {
str += "->";
str += ::to_string(values[i]);
}
ans.push_back(str);
values.pop_back();
return;
}
values.push_back(root->val);
solve(root->left, values, ans);
solve(root->right, values, ans);
values.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int>values;
vector<string>ans;
solve(root,values,ans);
return ans;
}
};
答案 1 :(得分:0)
您可以将递归与生成器一起使用:
def get_paths(d, _c = []):
val, _l, _r = d
if _l is None and _r is None:
yield [*_c, val]
if _l is not None:
yield from get_paths(_l, _c = _c+[val])
if _r is not None:
yield from get_paths(_r, _c = _c+[val])
print(list(get_paths((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]]
答案 2 :(得分:0)
这是一个更具可读性的递归生成器:
def paths(node):
if node is None:
return
val, *children = node
if any(children):
for child in children:
for path in paths(child):
yield [val] + path
else:
yield [val]
>>> list(paths(root))
[[1, 2, 4, 7], [1, 2, 5], [1, 3, 6]]
这还有为带有任意数量子节点的节点工作的额外好处。