LeetCode 144 Binary Tree Preorder Traversal

LeetCode 144 Binary Tree Preorder Traversal Problem

Download Code
# 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 __init__(self):
    #     self.result = []
    #
    # def preorderTraversal(self, root):
    #     """
    #     :type root: TreeNode
    #     :rtype: List[int]
    #     """
    #     if root is None:
    #         return []
    #     self.preorderTraversalHelper(root)
    #     return self.result
    #
    # def preorderTraversalHelper(self, node):
    #     if node is None:
    #         return
    #     self.result.append(node.val)
    #     self.preorderTraversalHelper(node.left)
    #     self.preorderTraversalHelper(node.right)

    def preorderTraversal(self, root):
        # stack
        if root is None:
            return []
        res = []
        stack = [root]
        while len(stack) > 0:
            curr = stack.pop()
            res.append(curr.val)
            if curr.right is not None:
                stack.append(curr.right)
            if curr.left is not None:
                stack.append(curr.left)
        return res

Download Binary Tree Preorder Traversal.py

List of all Binary Tree Preorder Traversal problems

Leetcode 144 Binary Tree Preorder Traversal problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

self.val = x

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.