144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

题目:

https://leetcode.com/problems/binary-tree-preorder-traversal/

难度:

Medium

Recursive

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

Iterative

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

推荐阅读更多精彩内容