简体   繁体   中英

Preorder Binary Tree traversal Recursive method

I was trying to understand implementation of Binary Tree traversal (PreOrder). The non recursive approach was fine, but I am totally lost while trying to understand the recursive approach.

Code:

def preorder_print(self, start, traversal): """Root->Left->Right"""
if start:
    traversal += (str(start.value) + "-")
    traversal = self.preorder_print(start.left, traversal)
    traversal = self.preorder_print(start.right, traversal)
return traversal

Binary Tree

    8
   / \
  4   5
 / \   \
2   1   6

My understanding is while reaching Node 2(8-4-2), left of that node 2 is None. So if start: condition would fail.

Below are my questions.

  1. After node2.left is None, how node2.right is traversed? (because if start: condition fails)
  2. After node1, how the logic moves to node5 which rootNode.right?

My understanding on recursion is poor, kindly help!

Watch this, see if this helps:

class Node(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None
    def addleft(self,value):
        self.left = Node(value)
    def addright(self,value):
        self.right = Node(value)
    def preorder_print(self, start, traversal='', depth=0): 
        print( " "*depth, start.value if start else "None" )
        if start:
            traversal += (str(start.value) + "-")
            print(' '*depth, "check left")
            traversal = self.preorder_print(start.left, traversal, depth+1)
            print(' '*depth, "check right")
            traversal = self.preorder_print(start.right, traversal, depth+1)
        return traversal

base = Node(8)
base.addleft(4)
base.left.addleft(2)
base.left.addright(1)
base.addright(5)
base.right.addright(6)

print( base.preorder_print( base ) )

Output:

 8
 check left
  4
  check left
   2
   check left
    None
   check right
    None
  check right
   1
   check left
    None
   check right
    None
 check right
  5
  check left
   None
  check right
   6
   check left
    None
   check right
    None
8-4-2-1-5-6-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM