Recursive BTPT in Python

  • 0


    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 
                if root.left != None:
                    for val in self.preorderTraversal(root.left):
                if root.right != None:
                    for val in self.preorderTraversal(root.right):
                return rList

Log in to reply

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