Python---Sequence creation of binary tree and three kinds of traversal

Source: Internet
Author: User

Binary trees (binary tree) is a very important structure in data structure, which has .... (many words are omitted here) .... and other excellent characteristics.

Before the brush leetcode on the topic of the tree all skipped, (ORZ: I this even data structure will not be the person brush J8leetcode Ah!!! )

So !!! Knock on the blackboard!!! today, I was at B station and I saw the contents of the tree in the data structure, and I used my shallow Python dafa to make some trees build and traverse.

About the establishment of the tree I think the sequence is the most intuitive for the user, the input is very good to write. (All right, I'm looking at the tree in the Leetcode input is the sequence input is very good)

Tree node definition

Code to

class Bstreenode (object):     def __init__ (self, data):         = data        = none        = None

This piece of code is too good to understand, OK, not BB.

Binary Tree Sequence establishment

Not much to say, first on the code

1 #The establishment of a two-fork tree is entered in sequence traversal mode, and the node does not exist with ' None '2 defCreattree (nodeList):3     ifNodelist[0] = =None:4         returnNone5Head =Bstreenode (nodelist[0])6Nodes =[head]7j = 18      forNodeinchNodes:9         ifNode! =None:TenNode.leftchild = (Bstreenode (nodelist[j])ifNODELIST[J]! = NoneElseNone) One nodes.append (node.leftchild) AJ + = 1 -             ifj = =Len (nodeList): -                 returnHead theNode.rightchild = (Bstreenode (nodelist[j])ifNODELIST[J]! = NoneElseNone) -J + = 1 - nodes.append (node.rightchild) -             ifj = =Len (nodeList): +                 returnHead

Creattree is the sequence of the establishment of a two-fork tree function, the passed parameter is a sequence traversal of the array, that is, the tree node from left to right, from the top down into the array, if a node does not exist, then use None to represent.

Like what:

The two-fork tree shown in the figure is required to enter a = [1,2,3,4,5,none,6,none,none,7,8], followed by the example of this binary tree to explain the code.

  • Line 3-4 to determine if the root node is empty. If the root node is empty, then the tree (Shuo) (GE) does not (j) Save (8), and it is OK to return directly.
  • Line 5 , the first element in the element list is taken out of the new root node, and finally the root node is returned
  • Line 6 , create a nodes list, to hold the nodes in the tree, each node is generated to put it into the list, can be seen as a queue (so it is not a special specification, because it is only the elements in the list, no popup first element), here the root node is stored.
  • Line 7 , create the variable J for the index of the element in NodeList, initially 1. Because the No. 0 element has already created the root node.
  • Line 8 , remove the nodes in the nodes list, and create the left and right child nodes
  • Line 9 , first determine whether the nodes is empty, if it is empty, there is no node here, there is no need to create child nodes, otherwise create child nodes
  • Line , create a left node for the node whose value is the corresponding value of index J, if nodelists[j] = = None means that there is no child node, you do not have to create, that is, children = None
  • Line One, add the newly created node to the nodes array so that it can continue to add child nodes for the for loop
  • The first line, J plus 1, so that each nodelist element corresponds to a node
  • Line , determine the value of J, if the NodeList value equals the total node has been added, directly back to the head root node to complete the establishment of the tree
  • Line 15-19 , add the right node for the node, and the logic to add the left node is the same, not to repeat the

Okay, the code comment is complete, and we'll explain it by combining examples:

  • nodeList = [1,2,3,4,5,none,6,none,none,7,8], the following node is uniformly represented by N (value)
  • Establish root node head = N (1), J=1, Len (nodeList) = 11
  • start for loop: Nodes = [n (1)]
    • Node is n (1), non-null
      • Nodelist[j]=nodelist[1]=2 is not empty, so new node n (2), n (1) left node is n (2), new node is put into nodes, then nodes=[n (1), N (2)] j+1=2, J not Overflow
      • Nodelist[j]=nodelist[2]=3 is non-null, so the new node n (3), n (1) Right node is n (3), the new node is put into nodes, then nodes=[n (1), N (2), N (3)], then j+1=3, J not Overflow
    • Node is n (2), non-null
      • Nodelist[j]=nodelist[3]=4 non-null, so new node n (4), N (2) left node is n (4), new node is put into nodes, then nodes=[n (1), N (2), N (3), N (4)], j+1=4, J not Overflow
      • nodelist[j]=nodelist[4]=5 non-empty, so the new node n (5), N (2) The right node is n (5), the new node is put into nodes, then nodes=[n (1), N (2), N (3), N (4), N (5)], j+1=5, J not Overflow
    • node is n (3), non-empty
      • nodelist[j]=nodelist[5]=none is empty, so the left node of N (3) is directly equal to none, and none is also put into nodes, Then Nodes=[n (1), N (2), N (3), N (4), N (5), None] j+1=6, J not overflow
      • nodelist[j]=nodelist[6]=6 non-empty, so new node n (6), N (3) The right node is n (6), the new node is put into nodes, then nodes=[n (1), N (2), N (3), N (4), N (5), None,n (6)], j+1=7, J no overflow
    • node is n (4), non-empty
      • nodelist[j]=nodelist[7]=none is empty, so the left node of N (4) is directly equal to none, and none is also put into nodes, Then Nodes=[n (1), N (2), N (3), N (4), N (5), None,n (6), None], j+1=8, J no overflow
      • nodelist[j]=nodelist[8]=none is empty, so the right node of N (4) is directly equal to none, while the none is also put into nodes, then nodes=[n (1), N (2), N (3), N (4), N (5), None,n (6), None,none], j+1=9, J no overflow
    • Node is n (5), non-null
      • Nodelist[j]=nodelist[9]=7 is not null, so new node n (7), N (5) left node is n (7), new node is put into nodes, then nodes=[n (1), N (2), N (3), N (4), N (5), None,n (6), None,none,n (9)] j+1=10, J not Overflow
      • Nodelist[j]=nodelist[10]=8 is not NULL, so the new node N (8), N (5) Right node is n (8), the new node is put into nodes, then nodes=[n (1), N (2), N (3), N (4), N (5), None,n (6), None,none,n (9), N (Ten)] j+1=11, J overflow
  • J Overflow, return head root node, end binary tree establishment

 PS: If node is empty, it will skip the empty node directly.

Binary Tree Traversal (divine recursion)

1. Pre-sequence traversal

# Head is the root node of the two fork tree def Preordertraverse (head):     if Head:         Print (Head.val)        Preordertraverse (Head.leftchild)        preordertraverse (head.rightchild)

2. Middle Sequence traversal

# Head is the root node of the two fork tree def Inordertrverse (head):     if Head:        Inordertrverse (head.leftchild)        print(head.val)        inordertrverse (Head.rightchild) 

3. Subsequent traversal

# Head is the root node of the two fork tree def Postordertraverse (head):     if Head:        Postordertraverse (Head.leftchild)        postordertraverse (head.rightchild)        print(head.val)

for the middle sequence traversal, it cost me Dickens draw a diagram of the program execution, the Red Arrows represent the process of program execution, and still take a = [1,2,3,4,5,none,6,none,none,7,8] as an example

So the order in which the programs are printed is: 4 2 7 5 8 1 3 6

In the end, I salute the Big Brother and wish you all a good learning.

"Reprint indicates source, thank you"

Python---Sequence creation of binary tree and three kinds of traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.