Data structure - and the tree depth first traversal (recursive and non-recursive, Python implementation)

In front of us the queues, stacks, linked lists, you hands-on practice yet? Today, we came to the part of the tree, the tree is a very important part in the data structure, there are many, many applications of the tree, the tree species there are many, many, today we have to create a common tree. Other kinds of trees by one for the future, I will tell you, I remember my article attention Oh ~

First, the tree shape is similar like this:

a tree

It is called a point above the topmost root of the tree, a tree can have only one root node, the node can have multiple child nodes below, the number of child nodes, we are not required here, but there is no child node is called leaf node.

Well, the basic concept of the tree on the introduction here, so much to do it again a thousand times not as good as hands-on, then we learn by doing, we create a tree:

tree

# 定义一个普通的树类
class Tree:
    def __init__(self, data):
        self.data = data
        self.children = []

    def get(self):
        return self.data
    
    def set(self):
        return self.data

    def addChild(self, child):
        self.children.append(child)

    def getChildren(self):
        return self.children

This is what we defined the class tree, the tree and to add three methods, namely, data acquisition node, node data set, add a child node, Getting child nodes.

Here is actually a type of tree node class, a number of such nodes may constitute a tree, and we used to represent The tree root.

Next we instantiate a tree:

# 初始化一个树
tree = Tree(0)
# 添加三个子节点
tree.addChild(Tree(1))
tree.addChild(Tree(2))
tree.addChild(Tree(3))
children = tree.getChildren()
# 每个子节点添加两个子节点
children[0].addChild(Tree(4))
children[0].addChild(Tree(5))
children[1].addChild(Tree(6))
children[1].addChild(Tree(7))
children[2].addChild(Tree(8))
children[2].addChild(Tree(9))

We instantiate a good tree probably look like this:
tree

OK, we have an example of a tree well, let's take it way are recursive and non-recursive breadth-first traversal:

Breadth-first traversal

Breadth-first traversal, that is, from top to bottom, from left to right on one level tree traversal.

When a breadth-first traversal non-recursive way, we need to use the type of queue described earlier, so let's define a queue class:

# 用以实现广度优先遍历
class Queue():
    def __init__(self):
        self.__list = list()

    def isEmpty(self):
        return self.__list == []

    def push(self, data):
        self.__list.append(data)
    
    def pop(self):
        if self.isEmpty():
            return False
        return self.__list.pop(0)

Breadth-first traversal achieved by the queue

As long as we use a queue node when the team let the children of the node of the team can be.

# 广度优先遍历
def breadthFirst(tree):
    queue = Queue()
    queue.push(tree)
    result = []
    while not queue.isEmpty():
        node = queue.pop()
        result.append(node.data)
        for c in node.getChildren():
            queue.push(c)
    return result

Call it:

print(breadthFirst(tree))

Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Recursive breadth-first traversal

# 递归方式实现广度优先遍历
def breadthFirstByRecursion(gen, index=0, nextGen=[], result=[]):
    
    if type(gen) == Tree:
        gen = [gen]
    result.append(gen[index].data)
    
    children = gen[index].getChildren()
    
    nextGen += children
    if index == len(gen)-1:
        if nextGen == []:
            return
        else:
            gen = nextGen
            nextGen = []
            index = 0
    else:
        index += 1
    breadthFirstByRecursion(gen, index, nextGen,result)

    return result

Call it:

print(breadthFirstByRecursion(tree))

Output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Depth-first traversal

Depth-first traversal, that is, from top to bottom, left to right, the first sub-node traversal node siblings and then traverse the node.

Non-recursive depth-first traversal way to achieve it, we need to use the previously introduced stack structure, so we now define a class stack it:

# 用以实现深度优先遍历
class Stack():
    def __init__(self):
        self.__list = list()

    def isEmpty(self):
        return self.__list == []

    def push(self, data):
        self.__list.append(data)
    
    def pop(self):
        if self.isEmpty():
            return False
        return self.__list.pop()

Stack implementation using the depth-first traversal

Realize the depth-first traversal, we can just pop in the node when the child nodes of this node can be pushed onto the stack from left to right.

# 深度优先遍历
def depthFirst(tree):
    stack = Stack()
    stack.push(tree)
    result = []
    while not stack.isEmpty():
        node = stack.pop()
        result.append(node.data)
        children = node.getChildren()
        children = reversed(children)
        for c in children:
            stack.push(c)
    return result

Call it:

# 深度优先遍历
print(depthFirst(tree))

Output:[0, 1, 4, 5, 2, 6, 7, 3, 8, 9]

Recursive depth-first traversal

# 递归方式实现深度优先遍历
def depthFirstByRecursion(tree, result=[]):
    result.append(tree.data)
    children = tree.getChildren()
    for c in children:
        depthFirstByRecursion(c, result)
    return result

Call it:

print(depthFirstByRecursion(tree))

Output:[0, 1, 4, 5, 2, 6, 7, 3, 8, 9]

Well, today we will introduce here the tree, for breadth-first traversal recursive implementation, you have a better way to do this? Please leave a message to tell me.

Guess you like

Origin www.cnblogs.com/dongyangblog/p/11204612.html