[Lintcode]66. Binary Tree Preorder Traversal/[Leetcode]144. Binary Tree Preorder Traversal

66. Binary Tree Preorder Traversal/144. Binary Tree Preorder Traversal

  • 本题难度: Easy/Medium
  • Topic: Binary Tree

Description

Given a binary tree, return the preorder traversal of its nodes' values.

Example
Given:

1

/ 2 3
/ 4 5
return [1,2,4,5,3].

Challenge
Can you do it without recursion?

我的代码

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Preorder in ArrayList which contains node values.
    """
    def preTrav(self,root,res):
        res.append(root.val)
        if root.left:
            res = self.preTrav(root.left,res)
        if root.right:
            res = self.preTrav(root.right,res)
        return res
    def preorderTraversal(self, root):
        # write your code here
        if root is None:
            return []
        res = []
        return self.preTrav(root,res)

别人的代码

def preorderTraversal(self, root):
    ret = []
    stack = [root]
    while stack:
        node = stack.pop()
        if node:
            ret.append(node.val)
            stack.append(node.right)
            stack.append(node.left)
    return ret

思路
我用了递归。
别人的用了栈。

上一篇:[Swift Weekly Contest 127]LeetCode1008. 先序遍历构造二叉树 | Construct Binary Search Tree from Preorder Trave


下一篇:627D Preorder Test