when doing a problem on the Leetcode, there are a lot of binary tree related topics of the test data is given by the list, the time of submission will sometimes appear some data pass, this need to debug locally, so you need to use a list to build a binary tree, convenient debugging. The two-fork tree nodes on the Leetcode are defined as follows:
1 class TreeNode (object): 2 def __init__ (self, x): 3 Self.val = x4 self.left = None5 self.right = None
Use the list to build the binary tree, and the two-fork tree hierarchy traversal, the first sequence traversal, the middle sequence traversal, the post-order traversal code is as follows:
1 fromCollectionsImportdeque2 3 4 classTree (object):5 def __init__(self):6Self.root =None7 8 defConstruct_tree (Self, values=None):9 if notvalues:Ten returnNone OneSelf.root =TreeNode (values[0]) AQueue =deque ([self.root]) -Leng =len (values) -Nums = 1 the whileNums <Leng: -node =Queue.popleft () - ifnode: -Node.left = TreeNode (Values[nums])ifValues[nums]ElseNone + queue.append (node.left) - ifNums + 1 <Leng: +Node.right = TreeNode (values[nums+1])ifVALUES[NUMS+1]ElseNone A queue.append (node.right) atNums + = 1 -Nums + = 1 - - defBFS (self): -RET = [] -Queue =deque ([self.root]) in whileQueue: -node =Queue.popleft () to ifnode: + ret.append (node.val) - queue.append (node.left) the queue.append (node.right) * returnret $ Panax Notoginseng defpre_traversal (self): -RET = [] the + defTraversal (head): A if notHead: the return + ret.append (head.val) - Traversal (head.left) $ Traversal (head.right) $ Traversal (self.root) - returnret - the defin_traversal (self): -RET = []Wuyi the defTraversal (head): - if notHead: Wu return - Traversal (head.left) About ret.append (head.val) $ Traversal (head.right) - - Traversal (self.root) - returnret A + defpost_traversal (self): theRET = [] - $ defTraversal (head): the if notHead: the return the Traversal (head.left) the Traversal (head.right) - ret.append (head.val) in the Traversal (self.root) the returnRet
test and use:
1 t = Tree ()2 t.construct_tree ([1, 2, None, 4, 3, none, 5])3print c6> T.bfs ()4print t.pre_traversal ()5print t.in_ Traversal ()6print t.post_traversal ()
Python transforms a given list into a binary tree