您的位置:首页 > 其它

用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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐