Recursive BTPT in Python


  • 0
    X

    Explanation:

    Recursive programming is easy and straightforward.

    1. Base condition: return [](empty list) when input is None.
    2. Step condition: if input is not None, append current node's value to the rList. And then proceed to Pre-traversal the Left and the Right.

    In this way, whatever the input is, its state will gradually change from initial state into base condition state and end the recursive program.

    class Solution:
        def preorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            rList = []
            if root == None:
                return rList 
            else:
                rList.append(root.val)
                if root.left != None:
                    for val in self.preorderTraversal(root.left):
                        rList.append(val)
                if root.right != None:
                    for val in self.preorderTraversal(root.right):
                        rList.append(val)
                return rList
    

Log in to reply
 

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