Java实现-二叉树先序,中序,后序遍历及递归,非递归遍历

对于二叉树的遍历一共存在两种类型:递归遍历和非递归遍历,针对每种类型有分为先序遍历,中序遍历和后序遍历。以下是六种遍历执行过程。

//先序遍历二叉树(递归形式)

public List<Integer> preOrder1(TreeNode root){
if( root != null){
reslist.add(root.val);
System.out.print(root.val+";");
preOrder1(root.leftchild);
preOrder1(root.rightchild);
}
return reslist;
}
//先序遍历二叉树(非递归形式)
public List<Integer> preOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
TreeNode node = root;
while(root != null || !nodestack.isEmpty()){
while( root != null ){
//先将根结点添加到顺序表中,然后是打印输出
reslist.add(node.val);
System.out.println(node.val+";");
nodestack.push(node);
node = node.leftchild;
}
//出栈顺序是:先是根结点,其次是左子树结点,最后是右子树结点
node = nodestack.pop();
node = node.rightchild;
}
return reslist;
}

//中序遍历二叉树(递归形式)
public List<Integer> InOrder1(TreeNode root){
if(root != null){
InOrder1(root.leftchild);
reslist.add(root.val);
System.out.print(root.val+";");
InOrder1(root.rightchild);
}
return reslist;
}
//中序遍历二叉树(非递归形式)
public List<Integer> InOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
TreeNode node = root;
while( node != null || !nodestack.isEmpty()){
//将结点存入栈中
while( node != null){
nodestack.push(node);
node = node.leftchild;
}
//出栈顺序先是最左端的结点 出栈,接着是根结点出栈,最后是右子树结点
node = nodestack.pop();
//将出栈结点添加到顺序表中,并打印输出
reslist.add(node.val);
System.out.print(node.val+";");
node = node.rightchild;
}
return reslist;
}

//后序遍历二叉树(递归形式)
public List<Integer> PostOrder1(TreeNode root){
if(root != null){
PostOrder1(root.leftchild);
PostOrder1(root.rightchild);
reslist.add(root.val);
System.out.println(root.val+";");
}
return reslist;
}
//后序遍历二叉树(非递归形式)
public List<Integer> PostOrder2(TreeNode root){
Stack<TreeNode> nodestack = new Stack<TreeNode>();
List<Integer> nodelist = new ArrayList<Integer>();
TreeNode node = root;
while( node != null || !nodestack.isEmpty()){
while( node != null || !nodelist.contains(node)){
nodestack.push(node);
node = node.leftchild;
}
if( !nodestack.isEmpty()){
node = nodestack.pop();
reslist.add(node.val);
System.out.print(node.val+";");
if( !nodestack.isEmpty()){
node = nodestack.peek();
node = node.rightchild;
}
}
}
return reslist;

}

说明:对于上述出现的reslist顺序表的定义在上一篇博客中以给出。点击打开链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值