当前位置:网站首页>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;
}
}边栏推荐
猜你喜欢
随机推荐
高等数学(第七版)同济大学 习题3-8 个人解答
Numpy数组处理(二)
方法的传递
十一、HikariCP源码分析之HouseKeeper
linux install redis using script
Small program WeChat positioning is not accurate
HMS Core audio editing service audio source separation and spatial audio rendering, helping to quickly enter the world of 3D audio
iNFTnews | 福布斯的Web3探索
[HDLBits brush questions] Verilog Language (4) Procedures and More Verilog Features section
SAP Gui 730 安装的问题
对不起,你很难赚到中年人的钱
leetcode122. Best Time to Buy and Sell Stock II
Add obsolete flag to pdf
An article to understand service governance in distributed development
解决报错 WARNING: IPv4 forwarding is disabled. Networking will not work.
解决reudx中的异步问题 applyMiddleware thunk
四、HikariCP源码分析之初始化分析一
GBASE 8s 用户标示与鉴别
小程序预览pdf
百度智能云章淼:详解企业级七层负载均衡开源软件BFE









