Saturday, September 13, 2014

Leetcode (Python): Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
   1
    \
     2
    /
   3
return [1,2,3].

Solution:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of integers
    def preorderTraversal(self, root):
        solution = []
        stack = []
        node = root
        while node != None or len(stack)>0:
            if node != None:
                solution.append(node.val)
                stack.append(node)
                node = node.left
            else:
                node = stack.pop().right
        return solution

No comments :

Post a Comment