当前位置:网站首页>BM23 二叉树的前序遍历
BM23 二叉树的前序遍历
2022-06-21 16:05:00 【程序员·小李】
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
递归最好理解:
public int[] preorderTraversal (TreeNode root) {
// write code here
if (root == null){
return new int[0];
}
List<Integer> result = new ArrayList<Integer>();
find(result, root);
int[] array = new int[result.size()];
for (int i = 0 ; i < result.size(); i++){
array[i] = result.get(i);
}
return array;
}
private void find(List<Integer> result, TreeNode node){
if (node == null){
return;
}
result.add(node.val);
find(result, node.left);
find(result, node.right);
}
迭代版:其实也是模拟了递归的流程,按根、左、右的顺序依次添加。
public int[] preorderTraversal (TreeNode root) {
// write code here
if (root == null){
return new int[0];
}
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
// 根节点入栈
stack.push(root);
while (!stack.empty()){
TreeNode current = stack.pop();
// 先根节点
result.add(current.val);
// 先入,后出
if (current.right != null){
stack.push(current.right);
}
// 后入,先出
if (current.left != null){
stack.push(current.left);
}
}
int[] array = new int[result.size()];
for (int i = 0 ; i < result.size(); i++){
array[i] = result.get(i);
}
return array;
}边栏推荐
猜你喜欢

Redis6.0新特性(上)

Your cache folder contains root-owned files, due to a bug in npm ERR! previous versions of npm which

栈的生长方向和内存生长方向

node服务器 res.end()中写中文,客户端中乱码问题的解决方法

20 pygame模块制作一个跳跃的小球游戏

MATLAB实现的基于对称TSP问题研究

module.exports指向问题

Serialization and deserialization of binary tree

牛客网:大数加法

Qt 知识:使用 QGraphicsPixmapItem类
随机推荐
钣金行业MES系统的特色需求
path. join() 、path. Basename() and path extname()
Iframe cross domain value transfer
Application of integrated servo motor and Schneider PLC tm241cec24t under CANopen Protocol
【Leetcode】297. Serialization and deserialization of binary tree (difficult)
SCAU软件工程基础
Starkrocks Lecture 2 basic operation (1)
clickhouse学习笔记2:基本使用教程
Move Protocol Beta测试版再调整,扩大总奖池
新增Razor组件支持代理连接RDP,JumpServer堡垒机v2.23.0发布
【mysql学习笔记12】分页查询
[issue 349] Interviewer: how to gracefully customize the ThreadPoolExecutor thread pool?
Integrated base scheme presentation
Three color mark removal method
[Error] ‘vector‘ was not declared in this scope
[MySQL learning notes 16] permission management
Template: p6114 [template] Lyndon Decomposition & runs (string)
即将步入大四,开始我最真情的告白
20 pygame模块制作一个跳跃的小球游戏
Matlab中xticks函数