Recursive BTPT in Python

Today I uploaded my first solution on Leetcode. Cheers!

Here is the content~

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 RLISTbinary-tree

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: