当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢
随机推荐
SAP MIGO 报错-在例程WERT_SIMULIEREN字段NEUER_PREIS中字段溢出
GBASE 8s 数据库的恢复
PointPillars 工程复现
六、HikariConfig配置解析
小程序预览pdf
leetcode122. Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II(简单)
SwiftUI CoreData 教程之如何加速搜索速度
GBASE 8s 数据库的逻辑日志备份
模型评价指标汇总(持续更新)
Small program WeChat positioning is not accurate
C. Color the Picture(贪心/构造)
怎样下载国内外专利?
linkedlist的用处之一:通过结构体成员的地址获取结构体变量的地址
【板栗糖GIS】arcmap—标注太长,如何换行显示
华为畅享50 Pro评测:HarmonyOS加持 更流畅更安全
GBASE 8s 数据库的智能大对象备份
五、HikariCP源码分析之初始化分析二
linux使用脚本安装redis
中科院TextMind(文心)安装及使用
JS教程之 ElectronJS 自定义标题栏









