当前位置:网站首页>NC193 二叉树的前序遍历
NC193 二叉树的前序遍历
2022-07-29 21:49:00 【syc596】
NC193 二叉树的前序遍历
二叉树的前序遍历_牛客题霸_牛客网 (nowcoder.com)
144. 二叉树的前序遍历
// //前序遍历-根左右
// //递归
// import java.util.*;
// public class Solution {
// public void preorder(List<Integer> list,TreeNode root){
// if(root==null){
// return;
// }
// list.add(root.val);
// preorder(list,root.left);
// preorder(list,root.right);
// }
// public int[] preorderTraversal (TreeNode root) {
// List<Integer> list=new ArrayList<>();
// preorder(list,root);
// int[] ret=new int[list.size()];
// for(int i=0;i<list.size();i++){
// ret[i]=list.get(i);
// }
// return ret;
// }
// }
// //迭代1
// import java.util.*;
// public class Solution {
// public int[] preorderTraversal (TreeNode root) {
// if(root==null){
// return new int[0];
// }
// List<Integer> list=new ArrayList<>();
// Stack<TreeNode> st=new Stack<>();
// st.push(root);
// while(st.isEmpty()==false){
// TreeNode cur=st.pop();
// list.add(cur.val);
// if(cur.right!=null){
// st.push(cur.right);
// }
// if(cur.left!=null){
// st.push(cur.left);
// }
// }
// int[] ret=new int[list.size()];
// for(int i=0;i<list.size();i++){
// ret[i]=list.get(i);
// }
// return ret;
// }
// }
//迭代2
import java.util.*;
public class Solution {
public int[] preorderTraversal (TreeNode root) {
List<Integer> list=new ArrayList<>();
Stack<TreeNode> st=new Stack<>();
TreeNode cur=root;
while(cur!=null||st.isEmpty()==false){
while(cur!=null){
list.add(cur.val);
st.push(cur);
cur=cur.left;
}
cur=st.pop();
cur=cur.right;
}
int[] ret=new int[list.size()];
for(int i=0;i<list.size();i++){
ret[i]=list.get(i);
}
return ret;
}
}边栏推荐
猜你喜欢

结合布林线理解现货白银走势图的方法

Official announcement!Suzhou Wujiang Development Zone launches electronic labor contract platform

百度智能云章淼:详解企业级七层负载均衡开源软件BFE

【板栗糖GIS】arcmap—如何在表格空值处进行批量求和

【板栗糖GIS】arcmap—标注太长,如何换行显示

【R语言】【2】绘图base和lattice和ggplot2库

怎样把某个公司所有的专利全部查到、一网打尽?

数据安全建设

【Verilog】Verilog设计进阶

Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-7 Individual Answers
随机推荐
php反序列化结构知识点实例分析
文献综述的写作技巧,掌握这些技巧,效率大大提高!
SAP MIGO 报错-在例程WERT_SIMULIEREN字段NEUER_PREIS中字段溢出
Add obsolete flag to pdf
【LeetCode】36、有效的数独
MySQL的TIMESTAMP数据类型
lambda表达式
微信小程序如何开通支付功能?
Add a logo to the upper left corner of the picture, add time and address to the lower left corner, and wrap the line when the address reaches the specified length
GBASE 8s自定义存储过程和函数介绍
03-树3 Tree Traversals Again(树的遍历)
GBASE 8s 如何通过脚本获取bufwait等统计信息
GBASE 8s 数据库的备份创建
linkedlist的用处之一:通过结构体成员的地址获取结构体变量的地址
E. XOR Tree(树形dp/异或/最近公共祖先)
网络通信编程基础,BIO,NIO
Numpy array processing (2)
Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-7 Individual Answers
【板栗糖GIS】arcmap—如何快捷替换属性表中的部分内容
转:idea中language level设置