【问题标题】:How to find the sum of nodes in a tree without recursion如何在没有递归的情况下找到树中节点的总和
【发布时间】:2020-01-22 09:44:58
【问题描述】:

我尝试了几种不同的方法来解决这个问题。

我的代码的节点定义为: 节点是一个对象
- 值:数字
- children:节点列表

class Node:
    def __init__(self, key, childnodes):
        self.key = key
        self.childnodes = childnodes

    def __repr__(self):
        return f'Node({self.key!r}, {self.childnodes!r})'


testTree = Node(1, [Node(2, []), Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])])

我已经接近用代码完成问题了:

def sum_of_nodes(root):
    sum = 0

    while root:
        sum += root.key
        print(sum)
        root = root.childnodes
        print(root)
        root = root.pop()
        print(root)

print(sum)

但是,它跳过了代码的某些部分,我不确定如何修复它。上面代码的结果是:

1
[Node(2, []), Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])]
Node(3, [Node(4, [Node(5, []), Node(6, [Node(7, [])])])])
4
[Node(4, [Node(5, []), Node(6, [Node(7, [])])])]
Node(4, [Node(5, []), Node(6, [Node(7, [])])])
8
[Node(5, []), Node(6, [Node(7, [])])]
Node(6, [Node(7, [])])
14
[Node(7, [])]
Node(7, [])
21
[]

还有一个错误:

Traceback (most recent call last):
  File "D:/Documents/project1.py", line 191, in <module>
    print(f'itersum_of_nodes(testTree) => {itersum_of_nodes(testTree)}')  # 28
  File "D:/Documents/project1.py", line 108, in sum_of_nodes
    root = root.pop()
IndexError: pop from empty list

我也尝试过 geeksforgeeks.org/inorder-tree-traversal-without-recursion/ 教授的方法,但是,我的子节点被定义为列表而不是 .right 或 .left,我不确定如何从中获取我需要的信息。代码是:

stack = []
    sum = 0
    current = root

    while True:
        if current.childnodes[0] is not None:
            stack.append(current)
            current = current.childnodes[0]
        elif stack:
            current = stack.pop()
            sum += current.value
            current = current.childnodes[1]
        else:
            break

【问题讨论】:

    标签: python-3.x tree


    【解决方案1】:

    这是一个工作版本的 while 循环,它无需递归即可遍历您的树。这样做的主要问题是您的节点不会单独存储子节点,而是作为列表存储。这意味着您需要警惕地检查节点实际有多少个子节点。

    def sum_of_nodes(root):
        sum = 0
        stack = []
    
        # While the current node is not none
        while root:
            # Add the value of the current node to the sum
            sum += root.key
            # Check if the current node has children
            if root.childnodes:
                # If it has two children, append the second child to the stack
                if len(root.childnodes) == 2:
                    stack.append(root.childnodes[1])
                # Set the first child as the current node
                root = root.childnodes[0]
            # If the current node doesn't have any children, take one from the stack
            elif stack:
                root = stack.pop()
            # If we run out of children in the stack, end the while loop
            else:
                break        
        return sum
    
    

    【讨论】:

      猜你喜欢
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      相关资源
      最近更新 更多