打印从根目录到每个目录的所有路径

2024-03-28 21:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

对于每个节点都提供以下元组的树:

(值,LeftNode,RightNode)

如何打印从根到叶的所有价值链?你知道吗

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

它应该表示以下树:

Example tree

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


Tags: 节点元组leftnoderightnode价值链
3条回答

下面是一个可读性更强的递归生成器:

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://leetcode.com/problems/binary-tree-paths/

在这里,您可以简单地开始使用dfs探索树,并在树中存储值,并维护从根到当前节点的所有值的向量。处理完该节点后,只需从该向量中移除当前节点处的值。当我们到达叶节点时,我们只需将向量中的值附加到我们的答案中。你知道吗

以下是在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;
  }
};

可以对生成器使用递归:

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]]

相关问题 更多 >