Two fork Tree
Composition
1. root node BinaryTree:Root
2, each node, have left dial hand node and right child node (can be empty) TreeNode:value,left, Right
Traversal of a binary tree:
Traverse binary Tree: Depth-first traversal, breadth-first traversal.
breadth: Traverse sibling nodes first, then traverse child nodes
Depth: traverse the child nodes first, then traverse the sibling nodes
depth Traversal result:50/20/60/15/30/70
breadth Traversal result:50/20/15/30/60/70
The depth traversal is divided into the first order, the middle order, the sequential traversal mode:
First Order traversal: first root node, then left subtree, then right sub-tree
First Order traversal result:50/20/15/30/60/70
Middle sequence traversal: First left subtree, then root node, then right sub-tree
Middle Sequence traversal result:15/20/30/50/60/70
Post-post traversal: First left subtree, then right subtree, then root node
Post-post traversal result:15/30/20/70/60/50
Code implementation:
# Encoding=utf-8
Class TreeNode (object): # defines a binary tree class
def __init__ (Self,val,left=none,right=none):
Self.val = Val
Self.left = Left
Self.right = Right
Class BinaryTree (object):
def __init__ (Self,root=none):
Self.root = root
Def prescan (self,retlist, node): # Sequence traversal: First, then left, then right
IF node! = None:
Retlist.append (Node.val)
Self.prescan (Retlist, Node.left)
Self.prescan (Retlist, Node.right)
Return retlist
def midscan (self, Retlist, node): # Middle sequence traversal: first left, back, right
IF node! = None:
Self.midscan (Retlist, Node.left)
Retlist.append (Node.val)
Self.midscan (Retlist, Node.right)
Return retlist
def postscan (self, Retlist, node): # post- traversal: First left, then right, followed by
IF node! = None:
Self.postscan (Retlist, Node.left)
Self.postscan (Retlist, Node.right)
Retlist.append (Node.val)
Return retlist
if __name__ = = ' __main__ ':
root = TreeNode (50)
Root.left = TreeNode (20,left=treenode), Right=treenode (30,right=treenode (12)))
Root.right = TreeNode (60,right=treenode (70))
BTree = BinaryTree (Root)
Retlist = Btree.prescan ([],btree.root)
Print Retlist
RetList2 = Btree.midscan ([],btree.root)
Print RetList2
RETLIST3 = Btree.postscan ([],btree.root)
Print RetList3
Python algorithm-two fork tree depth first traversal