首页 > 其他 > 详细

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

时间:2018-02-06 00:31:19      阅读:226      评论:0      收藏:0      [点我收藏+]

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 先序遍历二叉树

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!