用stack实现二叉树的中序遍历
2017-08-08 10:33
155 查看
二叉树的中序遍历
样例
给出二叉树
返回
样例
给出二叉树
{1,#,2,3},
1 \ 2 / 3
返回
[1,3,2].
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ import java.util.ArrayList; import java.util.Stack; public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result=new ArrayList<Integer>(); Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode curt=root; while(curt!=null||!stack.empty()){ while(curt!=null){ stack.add(curt); curt=curt.left; } curt=stack.peek(); result.add(curt.val); stack.pop(); curt=curt.right; } return result; } }
相关文章推荐
- leetcode | 二叉树的前序遍历、中序遍历、后续遍历的非递归实现
- python实现二叉树,前序遍历,中序遍历,后续遍历
- 杂七杂八——C#实现二叉树,外带中序遍历
- 二叉树(一) 先序遍历、中序遍历、后续遍历、层次遍历的递归与非递归实现
- 【数据结构】迭代器实现二叉树的中序遍历
- 二叉树相关操作(前序遍历,中序遍历,后序遍历,层次序遍历等)递归和非递归实现
- 组合模式实现二叉树先序遍历,中序遍历和后序遍历
- 杂七杂八——C#实现二叉树,外带中序遍历
- .如何不用递归实现二叉树的前序/后序/中序遍历?
- 实现二叉树的先序遍历、中序遍历、后序遍历的递归非递归算法以及层次遍历算法
- 二叉树 Java 实现 前序遍历 中序遍历 后序遍历 层级遍历 获取叶节点 宽度 ,高度,队列实现二叉树遍历 求二叉树的最大距离
- C++实现链式二叉树,操作包括初始化二叉树、前序遍历、中序遍历、后序遍历、层次遍历
- 用迭代器实现二叉树的中序遍历
- 二叉树的非递归实现中序遍历
- .Net 中泛型二叉树的实现和中序遍历
- 二叉树的实现&&递归和非递归方式前序、中序、后续遍历&&发现一个节点中序遍历的下一节点
- c++实现二叉树的先序遍历,中序遍历,后序遍历(递归方法)及运行实例结果
- 二叉树前后中序遍历的非递归实现
- 二叉树的中序遍历(非递归实现)
- Binary Tree Inorder Traversal 二叉树的中序遍历(C++:Iterative solution using stack)