# Binary Tree Inorder Traversal

150人阅读 评论(0)

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

For example:
Given binary tree {1,#,2,3},

   1
\
2
/
3


return [1,3,2].

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

public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
getInorderTraversal(root, list);
return list;
}

public void getInorderTraversal(TreeNode root,List<Integer> list){
if(root==null)
return;
getInorderTraversal(root.left, list);
getInorderTraversal(root.right, list);
}

public List<Integer> inorderTraversal(TreeNode root) {
Set<TreeNode> visited=new HashSet<TreeNode>();
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode p=stack.peek();
if(p.left!=null&&!visited.contains(p.left)){
stack.push(p.left);
}else{
p=stack.pop();
if(p.right!=null){
}
}
}
return result;
}

个人资料
等级：
访问量： 6万+
积分： 2795
排名： 1万+
最新评论