Thursday, February 21, 2019

LeetCode 145. Binary Tree Postorder Traversal

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# Postorder (Left, Right, Root)

class Solution1:
    #recursive
    def postorderTraversal(self, root: 'TreeNode') -> 'List[int]':
       
        def addToList(root):
            if root:
                self.result.insert(0, root.val)
                addToList(root.right)
                addToList(root.left)
       
        self.result = []
        addToList(root)
        return self.result

class Solution:
    #iterative
    def postorderTraversal(self, root: 'TreeNode') -> 'List[int]':
       
        if not root:
            return []
       
        i = -1
        result = [root]
        while i >= -len(result):
            temp = result[i]
            if temp.left:
                result.insert(i, temp.left)
            if temp.right:
                result.insert(i, temp.right)
            i -= 1

        vals = [i.val for i in result]
        return vals

No comments:

Post a Comment