前序遍历:
public class RetrieveTree {
public void preOrder(TreeNode root)
{ Stack<TreeNode>s=new Stack<TreeNode>();
while(root!=null||!s.isEmpty())
{
while(root!=null)
{
s.push(root);
System.out.print(root.val+" ");
root=root.left;
}
if(!s.isEmpty())
{
root=s.pop().right;
}
// }else
// root=null;
}
}
中序遍历:
public void inOrder(TreeNode root)
{ Stack<TreeNode>s=new Stack<TreeNode>();
while(root!=null||!s.isEmpty())
{
while(root!=null)
{
s.push(root);
root=root.left;
}
if(!s.isEmpty())
{
root=s.pop();
System.out.print(root.val+" ");
root=root.right;
}
}
}
后序遍历
public void postOrder(TreeNode root)
{ Stack<TreeNode>s=new Stack<TreeNode>();
List<Integer>li=new ArrayList<Integer>();
li.isEmpty();
TreeNode r=null;
while(root!=null||!s.isEmpty())
{
if(root!=null)
{
s.push(root);
root=root.left;
}
else{
root=s.peek();
if(root.right!=null&&root.right!=r)
root=root.right;//如果右节点没便利,则遍历右结点
else{
s.pop();
System.out.print(root.val+" ");
r=root;
root=null;
}
}
}
}