Home > Enterprise >  How to perform Binary Tree Postorder Traversal?
How to perform Binary Tree Postorder Traversal?

Time:06-20

The code will give a result of 4 2 1 3 6 5 7. How do I code it to transform into a postorder traversal?

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
    
def func1(nums):
    if not nums:
        return None
    mid_val = len(nums)//2
    node = TreeNode(nums[mid_val])
    node.left = func1(nums[:mid_val])
    node.right = func1(nums[mid_val 1:])
    return node

def func2(node): 
    if not node: 
        return      
    print(node.val)
    func2(node.left) 
    func2(node.right)   

result = func1([1, 2, 3, 4, 5, 6, 7])
func2(result)    

CodePudding user response:

In the post-order tree-traversal, first the left child node, then the right child node, and finally the parent node are printed. Accordingly, if you line up the same scenario for your func2 function, you should edit your code like this.

def func2(node):
    if not node:
        return
    func2(node.left)
    func2(node.right)
    print(node.val)
  • Related