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

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

题目

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

For example:

Given binary tree [1,null,2,3],

1    \     2    /   3

 

return [1,3,2].

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

链接:

5/10/2017

感觉大家都是默默的记住了这个算法,并没有很多的解释为什么这样子。。。

我来尝试一下:

打印左子树时候,parent还是在Stack里,打印右子树时候,parent不在stack里。

这个算法是在pop出来的时候add to ret,所以因为处理right时候,parent不需要在stack。处理左子树时候,还没有轮到parent,所以parent需要在Stack里。

是不是有这个规律?只要是parent值在当前值之后处理,parent就应该在stack里,而如果parent在当前值处理之前已处理完,parent就不在stack里。

1 public class Solution { 2     public List
inorderTraversal(TreeNode root) { 3 List
ret = new ArrayList
(); 4 if (root == null) return ret; 5 6 Stack
stack = new Stack
(); 7 TreeNode current = root; 8 // when processing left, parent is in stack 9 // when processing right, parent is no longer in stack10 while (current != null || !stack.empty()) {11 while (current != null) {12 stack.push(current);13 current = current.left;14 }15 current = stack.pop();16 ret.add(current.val);17 current = current.right;18 }19 return ret;20 }21 }

更多讨论

 

转载于:https://www.cnblogs.com/panini/p/6839089.html

你可能感兴趣的文章
使用CCleaner卸载chrome
查看>>
typeof和GetType的区别
查看>>
xtraTabbedMdiManager控件切换时控件不更新的问题
查看>>
为易信正名
查看>>
debian8.4 ibus中文输入法
查看>>
如何使用dos命令查看MySQL当前使用的数据库?
查看>>
猫眼电影爬取(一):requests+正则,并将数据存储到mysql数据库
查看>>
android的ArrayMap类
查看>>
2011年5款备受关注的开源 NoSQL 数据库
查看>>
2-4-1 元组
查看>>
476. Number Complement(补数)
查看>>
生成函数
查看>>
HTMl5的存储方式sessionStorage和localStorage详解
查看>>
BZOJ 4516: [Sdoi2016]生成魔咒——后缀数组、并查集
查看>>
《JAVA程序设计》实训第一天——《猜猜看》游戏
查看>>
普通用户 crontab 任务不运行
查看>>
第三次冲刺(三)
查看>>
android实现静默安装demo
查看>>
数据缓存方案
查看>>
HDU 1086:You can Solve a Geometry Problem too
查看>>