当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢

GTK进行rgb绘图

Advanced Mathematics (Seventh Edition) Tongji University Exercises 3-7 Individual Answers

普洛斯荣获两项“数据中心绿色等级评估”5A级认证

SAP Gui 730 安装的问题

INFTnews | Forbes Web3 exploration

VSCode 插件大全

Huawei Enjoy 50 Pro evaluation: HarmonyOS blessing is smoother and safer

SwiftUI CoreData 教程之如何加速搜索速度
一、HikariCP源码分析之获取连接流程一

聊聊阻容降压原理 和 实际使用的电路
随机推荐
SwiftUI CoreData 教程之如何加速搜索速度
高性能数据访问中间件 OBProxy(三):问题排查和服务运维
二叉树的操作集:(二叉树的定义,遍历)
阿里 P8 爆出的这份大厂面试指南,看完工资暴涨 30k!
聊聊阻容降压原理 和 实际使用的电路
02-SDRAM:自动刷新
The implementation of the flood control project and safety construction project in the flood storage and detention areas in Luluze and Ningjinbo was launched
MySQL的TIMESTAMP数据类型
IDEA 快捷键
JS教程之 ElectronJS 自定义标题栏
[BUG]memset和成员初始化的先后顺序
华为畅享50 Pro评测:HarmonyOS加持 更流畅更安全
都有哪些查找和下载英文文献的方法?
GBASE 8s 如何并行执行update statistics
D. Rain(思维/线性代数/差分数组)
24小时伦敦金走势图分析
线性回归的多种实现方式
install mysql using script
"Introduction to nlp + actual combat: Chapter 7: Dataset loading in pytorch and the use of its own datasets"
Leetcode 705.设计哈希集合