二叉树的递归和迭代实现(java)
作者:秋名山码民
- 2022 年 8 月 20 日 陕西
本文字数:1612 字
阅读完需:约 5 分钟
递归实现,
前序:根左右
中序:左根右
后续:左右根
package 二叉树;
public class 递归 {
public class Node{
public int value;
public Node Left;
public Node Right;
public Node(int data){
this.value = data;
}
}
public void preOrderRecur(Node head){
if(head == null){
return;
}
System.out.println(head.value+" ");
preOrderRecur(head.Left);
preOrderRecur(head.Right);
}
public void inOrederRecur(Node head){
if(head == null){
return;
}
inOrederRecur(head.Left);
System.out.println(head.value+" ");
inOrederRecur(head.Right);
}
public void posOrederRecur(Node head){
if(head == null){
return;
}
posOrederRecur(head.Left);
posOrederRecur(head.Right);
System.out.println(head.value+" ");
}
}
复制代码
迭代实现,
用自己的数据结构来代替函数栈的递归,凡是可以用递归的都能用迭代写出来
package 二叉树;
import java.util.Stack;
public class 非递归 {
public class Node{
public int value;
public Node Left;
public Node Right;
public Node(int data){
this.value = data;
}
}
//用自己的数据结构来模拟代替函数栈
public void preOrderUnRecur(Node head){
System.out.println("pre-order: ");
if(head != null){
Stack< Node> stack = new Stack<Node>();
stack.add(head);//插入根
while(!stack.empty()){
head = stack.pop();//弹出根
System.out.println(head.value+" ");
if(head.Right != null){
stack.push(head.Right);//栈的先进后出,最后左边会先打印
}
if(head.Left != null){
stack.push(head.Left);
}
}
}
System.out.println();
}
//中 zuo,根,you
public void inOrderUnRecur(Node head){
System.out.println("in-order: ");
if(head != null){
Stack<Node> stack = new Stack<Node>();
while(!stack.empty() || head != null){
if(head!=null){
stack.push(head);
head = head.Left; //一直放左,直到碰到根 左根右
}else{
head = stack.pop();
System.out.println(head.value+" ");
head = head.Right;
}
}
}
System.out.println();
}
//后 zuo,you,根
public void posOrderUnRecur(Node head){
System.out.println("pos-order: ");
if(head != null){
Stack<Node> s1 = new Stack<Node>();//俩个栈实现
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while(!s1.isEmpty()){
head = s1.pop();
s2.push(head);
if(head.Left != null){
s1.push(head.Left);
}
if(head.Right != null){
s1.push(head.Right);
}
}
while(!s2.isEmpty()){
System.out.println(s2.pop()+" ");
}
}
}
}
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 3
版权声明: 本文为 InfoQ 作者【秋名山码民】的原创文章。
原文链接:【http://xie.infoq.cn/article/f15f5bdd441dde81f125e1b5c】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
秋名山码民
关注
卷不死,就往…… 2021.10.19 加入
2019NOIP退役成员,华为云享专家,阿里云专家博主,csdn博主,努力进行算法分享,有问题欢迎私聊
评论