Binary Tree Inorder Traversal
2015-09-29 08:43
148 查看
(referrence: ProgramCreek)
The key to solve inorder traversal of binary tree includes the following:
The order of "inorder" is: left child -> parent -> right child
Use a stack to track nodes
Understand when to push node into the stack and when to pop node out of the stack
Note that inorder traversal of BST is an ascending array.
The key to solve inorder traversal of binary tree includes the following:
The order of "inorder" is: left child -> parent -> right child
Use a stack to track nodes
Understand when to push node into the stack and when to pop node out of the stack
Note that inorder traversal of BST is an ascending array.
Algorithm 1 -- Recursive
public class Solution { List<Integer> result = new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if(root !=null){ helper(root); } return result; } public void helper(TreeNode p){ if(p.left!=null) helper(p.left); result.add(p.val); if(p.right!=null) helper(p.right); } }
Algorithm 2 -- Iterative
public class Solution { public ArrayList<Integer> inorderTraversal(TreeNode root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ArrayList<Integer> lst = new ArrayList<Integer>(); if(root == null) return lst; Stack<TreeNode> stack = new Stack<TreeNode>(); //define a pointer to track nodes TreeNode p = root; while(!stack.empty() || p != null){ // if it is not null, push to stack //and go down the tree to left if(p != null){ stack.push(p); p = p.left; // if no left child // pop stack, process the node // then let p point to the right }else{ TreeNode t = stack.pop(); lst.add(t.val); p = t.right; } } return lst; } }
相关文章推荐
- React显示和提交数据
- Java动态代理-->Spring AOP
- 文件处理命令-文件处理命令
- UI10_3个tableView的省市区联动
- Android实战简易教程<二十四>(基于Baas的用户表查询功能实现!)
- 【Android】28日问题记录
- 手动修改DOS默认显示行数
- Android实战简易教程<二十三>(基于Baas的用户注册验证用户名是否重复功能!)
- 理解 OpenStack + Ceph (2):Ceph 的物理和逻辑结构 [Ceph Architecture]
- Android实战简易教程<二十二>(基于Baas的用户注册功能)
- for循环的执行顺序
- [喵神]手把手教你ARC——iOS/Mac开发ARC入门和使用
- sql
- 我的Android进阶之旅------>Android利用温度传感器实现带动画效果的电子温度计
- Seekbar thumb center
- UI10_UITableViewCell自适应高度
- SQL Server char nchar vchar nvarchar 辨析
- HDU 1080 Human Gene Functions--DP--(变形最长公共子)
- 【bzoj1670】【Usaco2006 Oct】【护城河的挖掘】【凸包】
- html5:localStorage储存