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

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

Given a binary tree, return the postorder traversal of its nodes' values.

For example:

Given binary tree {1,#,2,3},

1    \     2    /   3

 

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

[解题思路]

后序遍历的非递归相对来说比较难,根节点需要在其左右孩子都访问结束后才能被访问,因此对于任一节点,先将其入栈,如果p不存在左孩子和右孩子,则可以直接访问它;或者p存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该节点。若非上述两种情况,则将p的右孩子和左孩子依次入栈,这样就保证了每次去站定元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子在根节点前面被访问。

1 public ArrayList
postorderTraversal(TreeNode root) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 ArrayList
result = new ArrayList
(); 5 if(root == null){ 6 return result; 7 } 8 9 Stack
stack = new Stack
();10 TreeNode cur = null, pre = null;11 stack.push(root);12 13 while(!stack.empty()){14 cur = stack.peek();15 if((cur.left == null && cur.right == null) ||16 ((pre != null) && (cur.left == pre || cur.right == pre))){17 result.add(cur.val);18 pre = cur;19 stack.pop();20 } else {21 if(cur.right != null){22 stack.push(cur.right);23 }24 if(cur.left != null){25 stack.push(cur.left);26 }27 }28 29 }30 31 return result;32 }

 

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

你可能感兴趣的文章
JSON Web Token 简介
查看>>
小谈yii2中3个数据提供者及与GridView的搭配使用
查看>>
对于iOS性能优化的一点看法
查看>>
移动端字体大小调节器实现
查看>>
在开始第一个机器学习项目之前就了解的那些事儿
查看>>
运行eos节点之官网从节点
查看>>
数据可视化,个人经验总结(Echarts相关)
查看>>
ajax简单封装
查看>>
【360天】跃迁之路——程序员高效学习方法论探索系列(实验阶段118-2018.01.31)...
查看>>
扯点:FC - Formatting Context
查看>>
WebGL2系列之顶点数组对象
查看>>
[webpack3.8.1]Guides-3-Asset Management(资源管理)
查看>>
Linux下libevent库的基础安装和安装错误的解决方案以及使用
查看>>
Makefile 速查笔记
查看>>
Go基础学习二之常用命令、包、变量、常量、控制语句、range
查看>>
【前端自动化测试】Karma + Jasmine + RequireJS 的自动化测试实现
查看>>
Webpack + Vue2 + Koa2 构建应用
查看>>
Spring Boot自定义隐式JSON映射程序的最简单方法
查看>>
JavaScript学习篇--本地存储
查看>>
一份关于webpack2和模块打包的新手指南
查看>>