【LEETCODE】144-Binary Tree Preorder Traversal

来源:互联网 发布:淘宝激活windows7密钥 编辑:程序博客网 时间:2024/06/04 18:03

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

For example:

Given binary tree {1,#,2,3},

   1

    \

     2

    /

   3


return [1,2,3].


参考:

http://bookshadow.com/weblog/2015/01/28/leetcode-binary-tree-preorder-traversal/

http://www.geeksforgeeks.org/618/


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def preorderTraversal(self, root):        """        :type root: TreeNode        :rtype: List[int]        """                #if root is None:            #return []                ans=[]        stack=[]        top=root                while stack or top:           #top==root为空时,返回ans=[]                        if top is None:           #top不为空时,先走下几步                top=stack.pop()       #当top走到leave时,top取stack中存的右child                            ans.append(top.val)       #ans记录top,top先走左child,top有右child时,stack记录                        if top.right:                stack.append(top.right)                            top=top.left                    return ans



0 0
原创粉丝点击