【问题标题】:Print all paths from Root to each leaf打印从根到每个叶子的所有路径
【发布时间】:2019-03-01 14:58:55
【问题描述】:

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

(值,左节点,右节点)

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

例如: (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]

【问题讨论】:

  • 你尝试了什么?你被困在哪里了?你试过使用递归吗?您是否尝试过实施 BFS 或 DFS?
  • 我尝试使用递归,但它返回了一个列表列表,例如:[1,[2,[4,7]]],由于某种原因,最后一个有两个值,并且只有对于左节点。

标签: python algorithm tree


【解决方案1】:

您似乎正在尝试解决此问题: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;
  }
};

【讨论】:

  • 这看起来不像 Python
  • 我在描述中提出了我的想法。您可以简单地使用这个想法以您自己选择的语言来实现它。谢谢!
【解决方案2】:

这是一个更易读的递归生成器:

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

这有一个额外的好处,即适用于具有任意数量子节点的节点。

【讨论】:

    【解决方案3】:

    您可以将递归与生成器一起使用:

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

    【讨论】:

      猜你喜欢
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      相关资源
      最近更新 更多