【问题标题】:BST breadth-first-traversal including deleted nodesBST广度优先遍历,包括删除节点
【发布时间】:2019-03-09 15:09:16
【问题描述】:

鉴于这棵树:

         7
    5         9
  _  6      8  _ 
    _ _    _ _

我希望输出是:

[[Node(7)], [Node(5), Node(9)], [None, Node(6), Node(8), None], [None, None, None, None]]

因此,重要的是包含“无”并且输出是列表中的列表。

我尝试了很多东西,但这就是我现在所处的位置:

class Node(object):
  def __init__(self, key, value=None):
    self.key = key
    self.value = value
    self.parent = None
    self.left_child = None
    self.right_child = None
    self.height = 0 

def breadth_first_traversal(self):
  self.height = 1
  to_do = [self.root]
  if (self.root == None):
    return to_do
  output = []
  current_height = self.height
  output.append([str(node) for node in to_do])

  while (to_do):
    done = []
    current = to_do.pop(0)
    if (current.height > current_height):
      current_height += 1
    if (current.left_child):
      current.left_child.height = current_height + 1 
      to_do.append(current.left_child)
      done.append(current.left_child)
    elif (not current.left_child):
      done.append(None)
    if (current.right_child):
      current.right_child.height = current_height + 1 
      to_do.append(current.right_child)
      done.append(current.right_child)
    elif (not current.right_child):
      done.append(None) 
    output.append([str(node) for node in done])

  print(output)
  return output

现在的输出是:

[['7'], ['5', '9'], ['None', '6'], ['8', 'None'], ['None', 'None'], ['None', 'None']]

我理解它为什么要制作包含 2 个元素的列表,因为这就是我所说的它现在应该做的事情。我只是不知道如何考虑级别。

【问题讨论】:

    标签: python binary-search-tree breadth-first-search


    【解决方案1】:

    一种可能是找到所有节点,包括存储None的叶子,连同每个节点的深度,然后按深度分组:

    为简单起见,我创建了一个可以使用kwargs 轻松初始化的二叉树,以及遍历树并提供运行深度值的方法:

    from itertools import groupby
    
    class Node:
      def __init__(self, **kwargs):
         self.__dict__ = {i:kwargs.get(i, None) for i in ['left', 'right', 'value']}
      def get_depths(self, _count = 0):
        yield [_count, self.value]
        if self.left is not None:
          yield from self.left.get_depths(_count+1)
        else:
          yield [_count+1, None]
        if self.right is not None:
          yield from self.right.get_depths(_count+1)
        else:
          yield [_count+1, None]
    
    tree = Node(value=7, left=Node(value=5, right=Node(value=6)), right=Node(value=9, left=Node(value=8)))
    flattened = [[c for _, c in b] for _, b in groupby(sorted(list(tree.get_depths()), key=lambda x:x[0]), key=lambda x:x[0])]
    

    输出:

    [[7], [5, 9], [None, 6, 8, None], [None, None, None, None]]
    

    【讨论】:

      【解决方案2】:

      由于您使用的是二叉搜索树,因此将结果作为元组连接到数组是有意义的。

      如果您想根据数组的相对深度连接数组,那么您需要实现一个聚合器函数,该函数继续将元素附加到列表中,直到深度增加,此时列表将被保存并清除下一组。

      或者,您可以将您拥有的结果传递给一个帮助函数,该函数只是按照您想要的方式连接元素。

      编辑1:以下应该可以工作;但是,我还没有测试过。我只是将done 移到while 循环之外,这样它就不会在每次迭代后重新初始化。此外,我只在深度增加时将done 附加到output,因为此时没有其他元素需要处理。

      class Node(object):
        def __init__(self, key, value=None):
          self.key = key
          self.value = value
          self.parent = None
          self.left_child = None
          self.right_child = None
          self.height = 0 
      
      def breadth_first_traversal(self):
        self.height = 1
        to_do = [self.root]
        if (self.root == None):
          return to_do
        output = []
        current_height = self.height
        output.append([str(node) for node in to_do])
        done = []
      
        while (to_do):
          current = to_do.pop(0)
          if (current.height > current_height):
            current_height += 1
            output.append([str(node) for node in done])
            done = []
          if (current.left_child):
            current.left_child.height = current_height + 1 
            to_do.append(current.left_child)
            done.append(current.left_child)
          elif (not current.left_child):
            done.append(None)
          if (current.right_child):
            current.right_child.height = current_height + 1 
            to_do.append(current.right_child)
            done.append(current.right_child)
          elif (not current.right_child):
            done.append(None) 
      
        print(output)
        return output
      

      【讨论】:

      • 我觉得我现在正在使用“完成”列表执行此操作,但我不知道如何正确使用高度
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2016-02-15
      • 2011-07-12
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多