First, create a binary tree node. There is a data field, left and right pointer fields.
Copy codeThe Code is as follows:
#-*-Coding: utf-8 -*-
Class TreeNode (object ):
Def _ init _ (self, left = 0, right = 0, data = 0 ):
Self. left = left
Self. right = right
Self. data = data
Copy codeThe Code is as follows:
Class BTree (object ):
Def _ init _ (self, root = 0 ):
Self. root = root
Create Binary Tree manually
Copy codeThe Code is as follows:
Node1 = TreeNode (data = 1)
Node2 = TreeNode (node1, 0, 2)
Node3 = TreeNode (data = 3)
Node4 = TreeNode (data = 4)
Node5 = TreeNode (node3, node4, 5)
Node6 = TreeNode (node2, node5, 6)
Node7 = TreeNode (node6, 0, 7)
Node8 = TreeNode (data = 8)
Root = TreeNode (node7, node8, 'root ')
Bt = BTree (root)
The following binary tree is generated.
Copy codeThe Code is as follows:
# Generated Binary Tree
#------------------------
# Root
#7 8
#6
#2 5
#1 3 4
#
#-------------------------
In addition to creating node nodes manually, you can also create a create method that allows users to input and add Binary Tree nodes... Use the previous method to add, the Code is as follows:
Copy codeThe Code is as follows:
#-*-Coding: utf-8 -*-
Class TreeNode (object ):
Def _ init _ (self, left = 0, right = 0, data = 0 ):
Self. left = left
Self. right = right
Self. data = data
Class BTree (object ):
Def _ init _ (self, root = 0 ):
Self. root = root
Def is_empty (self ):
If self. root is 0:
Return True
Else:
Return False
Def create (self ):
Temp = input ('enter a value :')
If temp is '#':
Return 0
Treenode = TreeNode (data = temp)
If self. root is 0:
Self. root = treenode
Treenode. left = self. create ()
Treenode. right = self. create ()
Create a binary tree using create
Copy codeThe Code is as follows:
# Run the file in the interactive Interpreter
Bt = BTree ()
Bt. create ()
Enter a value: 9
Enter a value: 7
Enter a value: 6
Enter a value: 2
Enter a value: 1
Enter a value :'#'
Enter a value :'#'
Enter a value :'#'
Enter a value: 5
Enter a value: 3
Enter a value :'#'
Enter a value :'#'
Enter a value: 4
Enter a value :'#'
Enter a value :'#'
Enter a value :'#'
Enter a value: 8
Enter a value :'#'
Enter a value :'#'
The same effect can be obtained through create.