常考:
1. 能够结合队列、栈、链表、字符串等许多数据结构。
2. 需要掌握图的基本遍历方式,比如BFS、DFS。
3. 需要掌握递归函数的使用,并自己设计出递归过程。
4. 与实际工作紧密结合。
二叉树遍历
- 中前后(前序)
- 前中后(中序)
- 前后中(后序)
前序遍历
// 递归方式
public void PreOrderRecur(Node head){
if(head == null)
return;
System.out.println(head.val+" ");
PreOrderRecur(head.left);
PreOrderRecur(head.right);
}
public void PreOrderUnRecur(Node head){
if(head == null)
return;
Stack<Node> stack = new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
Node cur = stack.pop();
System.out.println(cur.val+" ");
if(cur.right != null)
stack.push(cur.right);
if(cur.left != null)
stack.push(cur.left);
}
}
中序遍历
// 递归方式
public void InOrderRecur(Node head){
if(head == null)
return;
InOrderRecur(head.left);
System.out.println(head.val+" ");
InOrderRecur(head.right);
}
public void InOrderUnRecur(Node head){
if(head == null)
return;
Node cur = head;
Stack<Node> stack = new Stack<Node>();
while(cur != null || !stack.isEmpty()){
if(cur != null){
stack.push(cur);
cur = cur.left;
}
else{
cur = stack.pop();
System.out.println(cur.val + " ");
cur = cur.right;
}
}
}
后序遍历
// 递归方式
public void PosOrderRecur(Node head){
if(head == null)
return;
PosOrderRecur(head.left);
PosOrderRecur(head.right);
System.out.println(head.val+" ");
}
public void PosOrderUnRecur(Node head){
if(head == null)
return;
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
Node cur = head;
s1.push(cur);
while (!s1.isEmpty()) {
cur = s1.pop();
s2.push(cur);
if(cur.left != null)
s1.push(cur.left);
if(cur.right != null)
s1.push(cur.right);
}
while (!s2.isEmpty()){
cur = s2.pop();
System.out.println(cur.val+" ");
}
}
public void PosOrderUnRecur(Node head){
if(head == null)
return;
Stack<Node> stack = new Stack<Node>();
stack.push(head);
Node h = head;
Node c = null;
while(!stack.isEmpty()){
c = stack.peek();
if(c.left != null && h != c.left && h != c.right)
stack.push(c.left);
else if(c.right != null && h != c.right)
stack.push(c.right);
else {
System.out.println(stack.pop().val+" ");
h = c;
}
}
}