Both Iterative and recursive solution


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            #return self.recursive_traverse(root,[])
            return self.iterative_traverse(root)
    
        def recursive_traverse(self, current, result):
            if current:
                result.append(current.val)
                self.recursive_traverse(current.left, result)
                self.recursive_traverse(current.right, result)
                return result
            else:
                return []
        
        def iterative_traverse(self, root):
            stack = []
            result = []
            if(root == None):
                return []
            stack.append(root)
            while len(stack) != 0:
                node = stack.pop()
                if node.right:
                    stack.append(node.right)
                if node.left:
                    stack.append(node.left)
                result.append(node.val)
            
            return(result)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.