简体   繁体   English

使用中序遍历打印二叉树

[英]Printing a Binary Tree using Inorder Traversal

I want to print a Binary Tree using Inorder Traversal, I have these functions and I'm wondering how I would go about writing a function to use them to print the binary tree.我想使用 Inorder Traversal 打印二叉树,我有这些函数,我想知道如何编写 function 来使用它们打印二叉树。 Any help massively appreciated.非常感谢任何帮助。

def inorder(self):
    if not self.is_empty():
      for p in self._subtree_inorder(self.root()):
        yield p

  def _subtree_inorder(self, p):
    if self.left(p) is not None:
      for other in self._subtree_inorder(self.left(p)):
        yield other
    yield p
    if self.right(p) is not None:
      for other in self._subtree_inorder(self.right(p)):
        yield other

  def positions(self):
    return self.inorder()

Here two possible solutions in Python, given the following binary search tree.给定以下二叉搜索树,这里有两种可能的解决方案 Python。

       20
      /  \
    10    30
         /  \
       35    40
        \
         37

Recursive traversal递归遍历

The recursion ends whenever a node is null. Call inorder_rec() first for the left subtree, then print the value of the current node, then print it for the right subtree.每当node为 null 时递归结束。首先为左子树调用inorder_rec() ,然后打印当前节点的值,然后为右子树打印它。

Traversal using generator使用生成器遍历

The approach is more or less the same (not surprisingly, as the algorithm is the same).该方法或多或少是相同的(毫不奇怪,因为算法是相同的)。 We first need to yield all the result from the left subtree, then we yield the value of the current node and last but not least we yield the keys from the right subtree.我们首先需要从左子树中yield所有结果,然后我们产生当前节点的值,最后但并非最不重要的是我们从右子树中产生键。

All together全部一起

class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.key = key


class Bst:
    def __init__(self):
        self.root = None

    def insert(self, key):
        self.root = self.insert_rec(self.root, key)

    def insert_rec(self, node, key):
        if node is None:
            return Node(key)
        if key == node.key:
            print(f"Key {key} already present! Ignoring value!")
            return node
        if key <= node.key:
            node.left = self.insert_rec(node.left, key)
        else:
            node.right = self.insert_rec(node.right, key)
        return node

    def inorder(self):
        self.inorder_rec(self.root)

    def inorder_rec(self, node):
        # end of recursion if current node is None
        if node is None:
            return
        # indorder means: left subtree, then own value, then right subtree
        self.inorder_rec(node.left)
        print(node.key)
        self.inorder_rec(node.right)

    def inorder_with_generator(self):
        # yield from inorder_genreator()
        yield from self.inorder_generator(self.root)

    def inorder_generator(self, node):
        # nothing to yield if node is None
        if node is not None:
            for node_data in self.inorder_generator(node.left):
                yield node_data
            yield node.key
            for node_data in self.inorder_generator(node.right):
                yield node_data


tree = Bst()
tree.insert(20)
tree.insert(10)
tree.insert(30)
tree.insert(40)
tree.insert(35)
tree.insert(37)

tree.inorder()
print(list(tree.inorder_with_generator()))

Expected output:预计 output:

10
20
30
35
37
40
[10, 20, 30, 35, 37, 40]

To avoid having to provide the root node as an argument every time I have added two functions which always start the traversal at the root node without the need to supply any parameters.为了避免每次都必须提供root作为参数,我添加了两个函数,它们总是在根节点处开始遍历而不需要提供任何参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM