Binary Tree Preorder Traversal

Given a binary tree, return thepreordertraversal of its nodes' values.

For example: Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

return[1,2,3].

Note:Recursive solution is trivial, could you do it iteratively?

递归:

# 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 not root:
            return []
        return [root.val]+self.preorderTraversal(root.left)+self.preorderTraversal(root.right)

非递归

非递归版本需要利用辅助栈来实现

  • 1.首先把根节点压入栈中

  • 2.此时栈顶元素即为当前根节点,弹出并访问即可

  • 3.把当前根节点的右子树和左子树分别入栈,考虑到栈是先进后出,所以必须右子树先入栈,左子树后入栈

  • 4.重复2,3步骤,直到栈为空为止

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

源码分析

  1. 对root进行异常处理

  2. 将root压入栈

  3. 循环终止条件为栈s为空,所有元素均已处理完

  4. 访问当前栈顶元素(首先取出栈顶元素,随后pop掉栈顶元素)并存入最终结果

  5. 将右、左节点分别压入栈内,以便取元素时为先左后右。

  6. 返回最终结果

复杂度分析

使用辅助栈,最坏情况下栈空间与节点数相等,空间复杂度近似为 , 对每个节点遍历一次,时间复杂度近似为 .

Last updated

Was this helpful?