码迷,mamicode.com
首页 > 其他好文 > 详细

144. Binary Tree Preorder Traversal 先序遍历二叉树

时间:2018-02-06 01:09:03      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:gpo   tom   bottom   order   ble   des   笔记   ref   not   

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

For example:
Given binary tree [1,null,2,3],

   1
         2
    /
   3

return [1,2,3].

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


  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def preorderTraversal(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: List[int]
  12. """
  13. res = []
  14. stack = [root]
  15. while stack and stack[0]:
  16. node = stack.pop()
  17. res.append(node.val)
  18. if node.right:
  19. stack.append(node.right)
  20. if node.left:
  21. stack.append(node.left)
  22. return res






144. Binary Tree Preorder Traversal 先序遍历二叉树

标签:gpo   tom   bottom   order   ble   des   笔记   ref   not   

原文地址:https://www.cnblogs.com/xiejunzhao/p/8419844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!