Leet-code144. Binary Tree Preorder Traversal
2024-09-21 15:08:03
这是一道将二叉树先序遍历,题目不难。
首先采用深搜递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static List<Integer> resultlist = new ArrayList<Integer>(); public static void dfs (TreeNode root ,boolean flag ) {
if(flag==true)
{
resultlist.clear();
}
if(root==null)
{
return ;
} resultlist.add(root.val); if(root.left!=null)
{
dfs(root.left,false);
}
if(root.right!=null)
{
dfs(root.right,false);
} } public static List<Integer> preorderTraversal(TreeNode root ) {
dfs(root,true);
return resultlist;
} }
非递归实现方式
public static List<Integer> preorderTraversal(TreeNode root ) {
List<Integer> result = new ArrayList<>(); if(root == null)
return result; Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root); while(!stack.empty()){
TreeNode n = stack.pop();
result.add(n.val); if(n.right != null){
stack.push(n.right);
}
if(n.left != null){
stack.push(n.left);
} }
return result;
}
最新文章
- PHP 对象 “==” 与 “===”
- winows下使用ssh服务远程登录vbox中的虚拟机
- Silverlight C1.Silverlight.FlexGrid 表格动态列
- C#关键字
- ajax连接池和XMLHttpRequest
- hadoop运行流程分析源代码级
- 需要我们了解的SQL Server阻塞原因与解决方法
- 简单的socket方法
- scala学习笔记1(表达式)
- Smobiler 4.4已正式发布!(Smobiler能让你在Visual Studio上开发APP)
- 【前端基础系列】理解bind方法使用与实现
- [Aaronyang] 写给自己的WPF4.5 笔记9[复杂数据处理三步曲,数据展示ListView泪奔2/3]
- idea导入eclipse中的maven项目
- DBGrid添加行号编写笔记
- python中logging日志基本用法,和进程安全问题
- 使用wsgiref库diy简单web架构
- 阿里云ECS购买优惠码
- 简单整理React的Context API
- HDU1950-Bridging signals-最长上升子序列
- django 自定义过滤器中的坑.
热门文章
- ng2父子模块通信@ViewChild和@Inject
- 微软开业网站----精华 http://www.microsoft.com/opensource/directory.aspx
- [xdoj1227]Godv的数列(crt+lucas)
- 日期组件wdatepicker
- VMWare虚拟机Bridged类型网卡ping不通的原因和解决办法
- 获得用户IP、城市、国家等信息的api接口
- ssm重新开发计科院新闻网站
- ue4 c++ anim notify
- 2014-10-24 NOIP欢乐赛
- 洛谷P2513 [HAOI2009]逆序对数列