
LeetCode(144):Binary Tree Preorder Traversal
发布日期:2021-05-15 10:07:09
浏览次数:12
分类:博客文章
本文共 1238 字,大约阅读时间需要 4 分钟。
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3}
, 1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递归法(用栈来还原递归过程):
public class Solution { static Listres = new ArrayList<>(); static Stack stack = new Stack<>(); public static List preorderTraversal_inStack(TreeNode root) { if(root == null) return new ArrayList (); stack.push(root); while(!stack.isEmpty()){ TreeNode tr = stack.pop(); res.add(tr.val); if(tr.right!=null){ stack.push(tr.right); } if(tr.left!=null){ stack.push(tr.left); } } return res; }
递归法:
public static ListpreorderTraversal(TreeNode root) { if(root==null) return new ArrayList (); res.add(root.val); while(root.right!=null||root.left!=null){ preorderTraversal(root.right); preorderTraversal(root.left); } return res; }
发表评论
最新留言
感谢大佬
[***.8.128.20]2025年05月03日 04时16分45秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Horizon Daas租户管理平台扩展分配时报:内部错误
2019-03-12
vcenter访问报503错误处理
2019-03-12
项目计划甘特图绘制说明
2019-03-12
09.QT应用程序启动外部exe文件
2019-03-12
1009. clion调试段错误
2019-03-12
C/C++:线性表之顺序表
2019-03-12
嵌入式系统试题库(CSU)
2019-03-12
图神经网络7日打卡营学习心得
2019-03-12
electronJS 开发linux App
2019-03-12
MbedOS 设备中的模数转换(ADC)
2019-03-12
【vue】setInterval的嵌套实例
2019-03-12
【SpringBoot】如何配置热部署
2019-03-12
【rabbitMQ】04 如何实现高可用?
2019-03-12
【自考】之信息资源管理(一)
2019-03-12
C# 文本框限制大全
2019-03-12
setup facatory9.0打包详细教程(含静默安装和卸载)
2019-03-12
ionic4 路由跳转传值
2019-03-12
CSDN 怎么写出好看的博客
2019-03-12