The establishment of binary tree and various implementations of traversal (python version)



Binary tree is a very important data structure, which plays an important role in interviews and daily development.

The first is the process of building a tree. Compared with the implementation of C or C++, it involves more complex pointer operations, but in object-oriented languages, there is no need to consider pointers, memory, etc. First we need to define a tree node, we use a node based on linked list design, first define a data field, followed by left and right children. The following definitions:

 

  # Definition of tree nodes

class Node:

    def __init__(self, data=-1, lchild=None, rchild=None):

        self.lchild = lchild # Indicates the left subtree

        self.rchild = rchild # Indicates the right subtree

        self.data = data # Indicates the data

 

 

domain There are two implementations of tree building, traversal tree building and hierarchical tree building. These two are implemented based on stack and queue respectively. Let's take a look at the most basic recursive tree building. The process of recursive tree building is nothing more than going all the way to the end, but you need to associate the left and right child nodes of the node with the rest of the nodes. So we can do it like this:

 

  def traversal_create(self, root):

data = input()

if data is "#":

return None

else:

root.data = data

root.lchild = self.traversal_create(root.lchild )

root.rchild = self.traversal_create(root.rchild)

return root

 

First of all, the parameter we pass in is a default node, and its data data field is -1, then we accept the input data, assign it to the node data field, and then recurse Now, associate the left and right child nodes. Generally speaking, it should not be difficult to understand.

Let's take a look at the implementation of hierarchical tree building. The so-called hierarchical tree building is actually a queue-based operation. Using the characteristics of first-in, first-out queues, every time we visit a node, it is stored in the queue, and the left and right children of the current node are to be traversed. Node, the queue pops up a node, and the subsequent operations are the same. Look at the code:

 

  def add(self, elem):

node = Node(elem)

# root node

if self.root.data == -1:

self.root = node

self.myQueue.append(self.root)

else:

treeNode = self.myQueue[0] # record node

if treeNode.lchild is None:

treeNode.lchild = node

self.myQueue.append(treeNode.lchild)

else:

treeNode.rchild = node

self.myQueue.append(treeNode.rchild)

self.myQueue.popleft() # Pop up the parent node of the left and right subtrees that have been processed

 

We input a data, then initialize a node according to the data, put it into the queue, and then access the operation.

Needless to say, the three-order traversal of the tree is based on recursion and is well understood. What about the traversal based on queues and stacks? Compared with the tree-building based on the queue, we can write the traversal based on the queue, and also use the queue to store the nodes, and then output the data of the left and right children:

 

  # Hierarchical traversal uses the queue

def queue_tarversal(self, root):

if root is None:

return

q = deque()

q.append(root)

while q:

node = q.pop()

print(node.data)

if node.lchild is not None:

q.append(node.lchild)

else:

q.append(node .rchild)

 

stack based? Associating the characteristics of the lower stack, we traverse all the way along the left subtree, use the stack to store elements, and then traverse the right child node after popping up:

 

  # Use the stack to traverse

def stack_traversal(self, root):

if root is None:

return

mystack = []

node = root

while node or mystack:

while node:

print(node.data)

mystack.append(node)

node = node.lchild

node = mystack.pop()

node = node.rchild The

 

data structure is the difficulty and the foundation, no matter what All should study hard.

Complete code:



  

   ''' Establishment and implementation of binary tree (recursive and non-recursive) '''

from collections import deque



# Definition of tree nodes

class Node:

    def __init__(self, data=-1, lchild=None, rchild=None) :

        self.lchild = lchild # Indicates the left subtree

        self.rchild = rchild # Indicates the right subtree

        self.data = data # Indicates the data field



class Create_Tree:

    def __init__(self):

        self.root = Node() # Indicates the node

        self.myQueue = deque() # Using queues won't have much memory overhead


    # Build tree hierarchically

    def add(self, elem):

        node = Node(elem)

        # root node

        if self.root.data == -1 :

            self.root = node

            self.myQueue.append(self.root)

        else:

            treeNode = self.myQueue[0] # record the node

            if treeNode.lchild is None:

                treeNode.lchild = node

                self.myQueue.append(treeNode. lchild )

            else:

                treeNode.rchild = node

                self.myQueue.append(treeNode.rchild)

                self.myQueue.popleft() # Pop up the parent node that has processed the left and right subtrees


    # Recursively build the tree

    def traversal_create(self, root):

        data = input()

        if data is "#":

            return None

        else:

            root.data = data

            root.lchild = self.traversal_create(root.lchild)

            root.rchild = self.traversal_create(root.rchild)

        return root


    # 前序遍历输出

    def digui(self, root):

        if root is None:

            return

        print(root.data)

        self.digui(root.lchild)

        self.digui(root.rchild)


    # 使用堆栈来遍历

    def stack_traversal(self, root):

        if root is None:

            return

        mystack = []

        node = root

        while node or mystack:

            while node:

                print(node.data)

                mystack.append(node)

                node = node.lchild

            node = mystack.pop()

            node = node.rchild


    # 层次遍历 使用队列

    def queue_tarversal(self, root):

        if root is None:

            return

        q = deque()

        q.append(root)

        while q:

            node = q.pop()

            print(node.data)

            if node.lchild is not None:

                q.append(node.lchild)

            else:

                q.append(node.rchild)



if __name__ == "__main__":

    elems = range(10)

    tree = Create_Tree()

    for i in elems:

        # Non-recursive tree building, mainly based on the characteristics of queue FIFO and breadth traversal Ideas

        tree.add(i)


    # Recursive tree building

    # tree.traversal_create(tree.root)


    # Recursive traversal

    tree.digui(tree.root)

    # Stack traversal

    # tree.stack_traversal(tree.root)

  

  View Code



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326406564&siteId=291194637