# 数据结构-二叉树遍历

63人阅读 评论(0)
import java.util.Stack;
/*
* 用递归和非递归实现二叉树的前序，中序。后序遍历
* */
public class Problem1 {
/*递归实现*/
public static void preOrderTraverse(BNode root){
if(root == null) return;
System.out.print(root.value + " ");
preOrderTraverse(root.left);
preOrderTraverse(root.right);
}

public static void inOrderTraverse(BNode root){
if(root == null) return;
inOrderTraverse(root.left);
System.out.print(root.value + " ");
inOrderTraverse(root.right);
}

public static void postOrderTraverse(BNode root){
if(root == null) return;
postOrderTraverse(root.left);
postOrderTraverse(root.right);
System.out.print(root.value + " ");
}
/*非递归实现*/
public static void preOrderTraverse1(BNode root){
if(root == null) return;
Stack<BNode> stack = new Stack<BNode>();
while( !stack.isEmpty()){
root = stack.pop();
System.out.print(root.value + " ");
}
System.out.println();
}

public static void inOrderTraverse1(BNode root){
if(root == null) return;
Stack<BNode> stack = new Stack<BNode>();
BNode cur = root;
while(!stack.isEmpty() || cur != null){
if(cur != null){
stack.push(cur);
cur = cur.left;
}else{
cur = stack.pop();
System.out.print(cur.value+" ");
cur = cur.right;
}
}
System.out.println();
}

public static void postOrderTraverse1(BNode root){
if(root == null) return;
Stack<BNode> s1 = new Stack<BNode>();
Stack<BNode> s2 = new Stack<BNode>();
BNode cur = root;
while(!s1.isEmpty()){
cur = s1.pop();
}
while( !s2.isEmpty()){
cur = s2.pop();
System.out.print(cur.value + " ");
}
System.out.println();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BNode n1 = new BNode(1);
BNode n2 = new BNode(2);
BNode n3 = new BNode(3);
BNode n4 = new BNode(4);
BNode n5 = new BNode(5);
BNode n6 = new BNode(6);
BNode n7 = new BNode(7);
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;

postOrderTraverse1(n1);
postOrderTraverse(n1);

}

}

public class BNode {
public int value;
public BNode left;
public BNode right;
public BNode(int valur){
this.value = valur;
}

@Override
public String toString() {
return "BNode [value=" + value + ", left=" + left + ", right=" + right
+ "]";
}

}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1553次
• 积分：146
• 等级：
• 排名：千里之外
• 原创：13篇
• 转载：5篇
• 译文：0篇
• 评论：0条
文章存档