樹的遍歷之----先序,中序,後序和層序遍歷
阿新 • • 發佈:2018-11-05
1先序、中序、後序遍歷(遞迴實現)
先序遍歷:中 左 右
中序遍歷:左 中 右
後序遍歷:左 右 中
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
//遞迴--先序
public static void preOrderRecur(Node head){
if(head == null){
return ;
}
System. out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//遞迴--中序
public static void inOrderRecur(Node head){
if(head == null){
return;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
//遞迴--後序
public static void posOrderRecur(Node head){
if(head == null){
return ;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
2先序,中序,後序遍歷(非遞迴)
//非遞迴--先序 :先壓右子節點,再壓左子節點
public static void preOrderUnRecur(Node head){
if(head != null){
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();//將根結點壓入棧
System.out.print(head.value + " ");//列印當前節點的值
if(head.right != null){
stack.push(head.right);
}
if(head.left != null){
stack.push(head.left);
}
}
}
System.out.println();
}
//非遞迴--中序
public static void inOrderUnRecur(Node head){
if(head != null){
Stack<Node> stack = new Stack<Node>();
while(!stack.isEmpty() || head != null){
if(head != null){
stack.push(head);
head = head.left;
}else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
//非遞迴--後序:順序為左右中
//思路:可先求“中右左”再逆序即可得到“左右中”,參考先序遍歷的“中左右”要求“中右左”,只需變換壓棧順序即可
public static void posOrderUnRecur(Node head){
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.print(s2.pop().value + " ");
}
}
System.out.println();
}
3 層序遍歷
//層序遍歷(用佇列實現,故而沒有遞迴方式)
public static void levelOrder(Node head){
if(head == null){
return;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(head);
while(!queue.isEmpty()){
head = queue.poll();
System.out.print(head.value + " ");
if(head.left != null){
queue.offer(head.left);
}
if(head.right != null){
queue.offer(head.right);
}
}
}