二叉树

一、构建二叉树及其遍历

class Node(object):
    """二叉树节点"""
    def __init__(self, item):
        self.item = item
        self.left_child = None
        self.right_child = None

class BinaryTree(object):
    """二叉树"""
    def __init__(self):
        self.root = None

    def add(self, item):
        """添加节点"""
        node = Node(item)
        if self.root is None:
            self.root = node
            return None
        else:
            q = []
            q.append(self.root)
            while q:
                current_node = q.pop(0)
                if current_node.left_child is None:
                    current_node.left_child = node
                    return None
                else:
                    q.append(current_node.left_child)
                if current_node.right_child is None:
                    current_node.right_child = node
                    return None
                else:
                    q.append(current_node.right_child)

    def breadth_travel(self):
        """利用队列实现树的层次遍历"""
        if self.root is None:
            return None
        else:
            q = []
            q.append(self.root)
            while q:
                current_node = q.pop(0)
                print(current_node.item)
                if current_node.left_child is not None:
                    q.append(current_node.left_child)
                if current_node.right_child is not None:
                    q.append(current_node.right_child)

    def prev_travel(self, node):
        """先序遍历:根->左->右"""
        if node is None:
            return None
        else:
            print(node.item)
            self.prev_travel(node.left_child)
            self.prev_travel(node.right_child)

    def mid_travel(self, node):
        """中序遍历:左->根->右"""
        if node is None:
            return None
        else:
            self.mid_travel(node.left_child)
            print(node.item)
            self.mid_travel(node.right_child)

    def post_travel(self, node):
        """后序遍历:左->右->根"""
        if node is None:
            return None
        else:
            self.post_travel(node.left_child)
            self.post_travel(node.right_child)
            print(node.item)

b_tree = BinaryTree()
for i in range(10):
    b_tree.add(i)

print("层次遍历:")
b_tree.breadth_travel()
print("先序遍历:")
b_tree.prev_travel(b_tree.root)
print("中序遍历:")
b_tree.mid_travel(b_tree.root)
print("后序遍历:")
b_tree.post_travel(b_tree.root)
View Code

二、已知二叉树的先序遍历和中序遍历,求二叉树的后序遍历?

 

posted @ 2019-04-08 20:54  就俗人一个  阅读(171)  评论(0编辑  收藏  举报