数据结构之二叉树

187 阅读1分钟

二叉树的基本概念

在计算机科学中,二叉树(英语:Binary tree)是每个节点最多只有两个分支(即不存在分支度大于2的节点)的树结构。通常分支被称作“左子树”或“右子树”。二叉树的分支具有左右次序,不能随意颠倒。

       1
     /   \
    2     3
   / \    /
  4   5  6
        / \
       7   8

遍历

前序遍历(根左右)

前序遍历顺序:12453678

中序遍历(左根右)

中序遍历顺序:42517683

后序遍历(左右根)

后序遍历顺序:45278631

前序遍历实现

class Node(object):
    def __init__(self, index):
        self.index = index
        self.left_child = None
        self.right_child = None

class BinaryTree(object):
    def __init__(self, root):
        self.root = root
    def pre_travel(self, node):
        if not node:
            return
        print(node.index)
        self.pre_travel(node.left_child)
        self.pre_travel(node.right_child)
node_dict = {}
for i in range(1, 10):
    node_dict[i] = Node(i)
node_dict[1].left_child = node_dict[2]
node_dict[1].right_child = node_dict[3]
node_dict[2].left_child = node_dict[4]
node_dict[2].right_child = node_dict[5]
node_dict[3].left_child = node_dict[6]
node_dict[6].left_child = node_dict[7]
node_dict[6].right_child = node_dict[8]
tree = BinaryTree(node_dict[1])
tree.pre_travel(tree.root)