Python solution with detailed explanation


  • 0
    G

    Solution

    Binary Tree Preorder Traversal https://leetcode.com/problems/binary-tree-preorder-traversal/?tab=Description

    Algorithm

    • Use a stack to simulate the recursion.
    • Only add non-null children.
    class Solution(object):
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if root == None:
                return []
            st, result = [root], []
            while len(st):
                x = st.pop()
                result.append(x.val)
                if x.right:
                    st.append(x.right)
                if x.left:
                    st.append(x.left)
            return result
    

Log in to reply
 

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