请递归,非递归方式分别前序遍历,中序遍历,后续遍历二叉树
public class TraversalTree{
public static class Node {
public int value;
public Node left;
public Node right;
}
// 前序递归
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.println(head.value + " ");
inOrderRecur(head.right);
}
//后序递归
public static void posOrderRecur(Node head) {
if (head == null) {
return;
}
posOrderRecur(head.left);
System.out.println(head.value + " ");
posOrderRecur(head.right);
}
//非递归前序遍历
public static void preOrderUnRecur(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()) {
Node node = stack.pop();
System.out.println(node.value + " ");
if (node.left != null) {
node.push(node.left);
}
if (node.right != null) {
node.push(node.right);
}
}
}
//非递归中序遍历
public static void inOrderUnRecur(Node head) {
if (head == null) {
return;
}
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.println(head.value + " ");
head = head.right;
}
}
}
//非递归后续遍历
public static void postOrderUnRecur(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.println(s2.pop().value + " ");
}
}
}
}
网友评论