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

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [1,2,3] Solution 1:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
stack, res = [], []
if root is None:
return res
stack.append(root)
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return res

Solution 2:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Deque<TreeNode> queue = new LinkedList<>();
queue.offerFirst(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.pollFirst();
res.add(cur.val);
if (cur.right != null) {
queue.offerFirst(cur.right);
}
if (cur.left != null) {
queue.offerFirst(cur.left);
}
}
return res;
}
}
 

最新文章

  1. Partition:Partiton Scheme是否指定Next Used?
  2. 【推荐】CentOS安装vsftpd-3.0.2+安全配置
  3. 模板函数(template function)出现编译链接错误(link error)之解析
  4. 【ipv6惹的祸】curl 超时
  5. MySQL字符集乱码
  6. Win7开始菜单之【附件】不全解决方案
  7. HDU4861:Couple doubi(费马小定理)
  8. How to enable $Admin Shares in Windows 7
  9. SpringBoot Quickstart
  10. MVC中的Views下面的视图放到Views文件夹外
  11. UIButton UIImage 用法分析
  12. TCP连接建立系列 — TCP选项解析
  13. Spring Boot 1.5升级2.1 主要问题汇总
  14. ELK-logstash-6.3.2-常用配置
  15. AC自动机-HDU2222-模板题
  16. 下载imagenet2012数据集,以及label说明
  17. 【SpringBoot系列2】SpringBoot整合Redis
  18. css规范 - bem
  19. 对position的认知观
  20. NOSQL学习之一:Memcached, Redis, MongoDB区别

热门文章

  1. 落地即王道,锁死企业智变CP——云+AI
  2. 【One by one系列】一步步学习TypeScript
  3. 2019年阿里java面试题
  4. PAT B1095 解码PAT准考证
  5. POJ 1850:Code 组合数学
  6. Dynamics CRM - 为 Form 或者字段设置 Error Notification
  7. uploadify ASP.net 使用笔记
  8. EXCEL快速实现下拉计算快捷键
  9. springboot的http监控接口启动器的配置
  10. static_cast 与 dynamic_caste, reinterpreter 的区别