leetcode [python] 【144】 Binary Tree Preorder Traversal

why小曼發表於2016-04-07

思路一:遞迴方法

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

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root == None:
            return []
        return [root.val] + (self.preorderTraversal(root.left)) + (self.preorderTraversal(root.right)) 

思路二:非遞迴

使用資料結構棧,相當於層次遍歷的思路。

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

class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        top = root
        stack =[]
        while top or stack:
            if top == None:
               top = stack.pop() 
            res.append(top.val)
            if top.right:
                stack.append(top.right)
            top = top.left
        return res


相關文章