对于每个节点都具有以下元组的树:
(Value,LeftNode,RightNode)
如何打印从根到每个叶的所有价值链?
例如:(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
发布于 2019-03-01 23:37:26
看起来您正在尝试解决这个问题:https://leetcode.com/problems/binary-tree-paths/
在这里,您可以简单地使用dfs开始探索tree,并在tree中向下存储这些值,并维护从根到当前节点的所有值的向量。处理完该节点后,只需将当前节点的值从该向量中删除即可。当我们到达叶子节点时,我们简单地将向量中的值附加到我们的答案。
下面是用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;
}
};发布于 2019-03-01 23:01:28
您可以对生成器使用递归:
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]]发布于 2019-03-01 23:52:44
下面是一个可读性更好的递归生成器:
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]]这有一个额外的好处,即可以处理具有任意数量子节点的节点。
https://stackoverflow.com/questions/54947164
复制相似问题