【问题标题】:Function to count number of nodes to the left of root in Tree [duplicate]计算树中根左侧的节点数的函数[重复]
【发布时间】:2019-04-14 07:15:32
【问题描述】:

如何计算根节点左侧的节点数?这与计算树中的所有左侧节点不同。

【问题讨论】:

  • 遍历树并跟踪到根节点的距离,如果你向左走你做+1,如果你向右走你做-1,如果距离为正(或非)增加计数-否定取决于您对“向左”的解释)。
  • 欢迎来到 SO!:) 也许最好先在 Google 上搜索您的问题!
  • 如果您知道如何计算树中的节点数(请参阅重复参考),则将其应用于左子树。

标签: algorithm


【解决方案1】:

您应该通过跟踪根与所有其他节点之间的水平距离来计算根左侧的节点。 按顺序遍历树并记住当前位置(如果您向左走,则 +1,如果向右走,则 -1)应该足以完成这项工作。

def count_left(tree, current_position):
    if tree is None:
        return 0

    is_left = 1 if current_position > 0 else 0
    return is_left + count_left(tree.right, current_position -1) + count_left(tree.left, current_position +1)

count_left(tree.left, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多