博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary Tree Traversal
阅读量:6179 次
发布时间:2019-06-21

本文共 3241 字,大约阅读时间需要 10 分钟。

PostOrder

public class Solution {    // Important, when you pop a node, ensure its children are traversed.    public List
postorderTraversal(TreeNode root) { ArrayDeque
s = new ArrayDeque(); List
ans = new ArrayList
(); TreeNode cur = root; while (cur != null || !s.isEmpty()) { while (cur != null) { s.push(cur); cur = cur.left; } while (!s.isEmpty() && cur == s.peek().right) { cur = s.pop(); ans.add(cur.val); } if (s.isEmpty()) cur = null; else cur = s.peek().right; } return ans; } }

PreOrder

public class Solution {    public List
preorderTraversal(TreeNode root) { List
res = new LinkedList
(); ArrayDeque
stk = new ArrayDeque
(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ if(cur != null) { stk.push(cur); res.add(cur.val); // add val before going to children cur = cur.left; } else { TreeNode node = stk.pop(); cur = node.right; } } return res; }}

InOrder

public class Solution {    public List
inorderTraversal(TreeNode root) { List
res = new ArrayList
(); if(root == null) return res; ArrayDeque
stk = new ArrayDeque
(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ if(cur !=null) { stk.push(cur); cur = cur.left; } else { TreeNode node = stk.pop(); res.add(node.val); // add after all left children node = node.right; } } return res; }}

PreOrder

public class Solution {    public List
preorderTraversal(TreeNode root) { List
res = new LinkedList
(); ArrayDeque
stk = new ArrayDeque
(); if(root == null) return res; TreeNode cur = root; stk.push(cur); while(!stk.isEmpty()){ cur = stk.pop(); res.add(cur.val); if(cur.right != null) stk.push(cur.right); if(cur.left != null) stk.push(cur.left); } return res; }}

InOrder

public class Solution {    public List
inorderTraversal(TreeNode root) { List
res = new ArrayList
(); if(root == null) return res; ArrayDeque
stk = new ArrayDeque
(); TreeNode cur = root; while(cur != null || !stk.isEmpty()){ while(cur != null) { stk.push(cur); cur = cur.left; } cur = stk.pop(); res.add(cur.val); cur = cur.right; } return res; }}

转载地址:http://qjdda.baihongyu.com/

你可能感兴趣的文章
如何在 Linux 中统计一个进程的线程数
查看>>
NVIDIA新作解读:用GAN生成前所未有的高清图像(附PyTorch复现) | PaperDaily #15
查看>>
CString、CTime和COleDateTime转换
查看>>
在linux虚机中装vmtools
查看>>
WCF技术剖析之十三:序列化过程中的已知类型(Known Type)
查看>>
linux设备驱动程序--类class的实现
查看>>
中国云计算应用进入集中爆发期
查看>>
算法精解---计数排序
查看>>
DockOne微信分享(一二八):容器如何监控?
查看>>
谈谈分布式事务(Distributed Transaction)[共5篇]
查看>>
如何确保快递“最后一公里” ,亚马逊打算送到你的汽车后备箱
查看>>
Gartner:财务应用迁移到云 速度超出预期
查看>>
阿里云向物流业渗透 货运司机受益
查看>>
灾难恢复的人为因素:经理们应该做的10件事情
查看>>
中国教育行业可能到了最不平凡的10年:要么创新,要么死亡
查看>>
学习Docker的User Namespace
查看>>
Symantec Backup Exec 2012 Agent for Linux 卸载
查看>>
用EJB进行事务管理
查看>>
Linux Shell脚本系列之一
查看>>
数据可视化,个人经验总结(Echarts相关)
查看>>