需要多写几遍,形成肌肉记忆,好多题目都是这样子进行解答的!!!
结构
class Node{
int val;
Node left;
Node right;
Node(){
}
Node(int val){
this.val = val;
}
}
先序,中序,后序遍历(包括非递归)
// 先序递归
public static void preOrderRecur(Node head){
if(head == null)
return;
System.out.print(head.val + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
// 中序递归
public static void inOrderRecur(Node head){
if(head == null)
return;
inOrderRecur(head.left);
System.out.print(head.val + " ");
inOrderRecur(head.right);
}
// 后序递归
public static void posOrderRecur(Node head){
if(head == null)
return;
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.val + " ");
}
// 先序非递归
public static void preOrderUnRecur(Node head){
System.out.println("pre-order: ");
if(head != null){
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();
System.out.print(head.val + " ");
if(head.right != null)
stack.push(head.right);
if(head.left != null)
stack.push(head.left);
}
}
System.out.println();
}
// 后序非递归(进栈顺序为头右左,压入另一个栈)
public static void posOrderUnRecur(Node head){
System.out.print("pos-order: ");
if(head != null){
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack2 = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();
stack2.push(head);
if(head.right != null)
stack.push(head.right);
if(head.left != null)
stack.push(head.left);
}
while(! stack2.isEmpty()){
System.out.print(stack2.pop().val + " ");
}
}
System.out.println();
}
// 中序非递归遍历(每颗子树整棵树左边界进栈,依次弹得过程中,
// 打印,对弹出的节点右子树压栈,然后循环)
// 后序非递归
public static void inOrderUnRecur(Node head){
System.out.println("in-order: ");
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.val + " ");
head = head.right;
}
}
}
System.out.println();
}
// 广度优先搜索
public static void BFS(Node head){
if(head == null)
return;
System.out.print("BFS: ");
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while(!queue.isEmpty()){
Node cur = queue.poll();
System.out.print(cur.val + " ");
if(cur.left != null)
queue.add(cur.left);
if(cur.right != null)
queue.add(cur.right);
}
}
已知后序与中序输出前序(先序)(待完善)
计划用递归和非递归都写一下,加班加点Coding....
加几个链接吧,回头给写上