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