python创建中序二叉树并按照中序print

使用python创建二叉树

实现:

  1. 如果二叉树为空,则创建二叉树实例
  2. 如果当前结点为空,则创建结点。否则判断:
    • 如果输入值小于当前结点值,则添加到左结点
    • 如果输入值大于或等于当前值,则添加到右结点

代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


class Node(object):
        """docstring for Node"""

        def __init__(self, arg):
                super(Node, self).__init__()
                self.val = arg
                self.left = None
                self.right = None


class Tree(object):
        """docstring for Tree"""

        def __init__(self):
                super(Tree, self).__init__()
                self.root = None

        def init_tree(self, val, node=None):
                if node is None:
                        node = self.root
                if self.root is None:
                        self.root = Node(val)

                else:
                        if val < node.val:
                                if node.left is not None:
                                        self.init_tree(val, node.left)
                                else:
                                        node.left = Node(val)
                        else:
                                if node.right is not None:
                                        self.init_tree(val, node.right)
                                else:
                                        node.right = Node(val)

        def print_tree(self):
                """docstring for print_tree"""
                if self.root is not None:
                        self.print_tree_node(self.root)
                else:
                        print("it's an empty tree")

        def print_tree_node(self, node):
                """docstring for print_tree"""
                if node is not None:
                        self.print_tree_node(node.left)
                        print(node.val)
                        self.print_tree_node(node.right)

if __name__ == '__main__':
        tree = Tree()
        #  print(tree)
        tree.init_tree(3)
        tree.init_tree(4)
        tree.init_tree(7)
        tree.init_tree(5)
        tree.init_tree(1)
        tree.print_tree()

运行结果

python创建中序二叉树并按照中序print_第1张图片

参考:
http://stackoverflow.com/questions/2598437/how-to-implement-a-binary-tree-in-python

你可能感兴趣的:(python,算法)