class Tree{
Object value;
Tree left;
Tree right;
public Tree(Object value){
this.value=value;
}
}
1.使用递归法实现二叉树的先序、中序、后序遍历
public static void orderRecur(Tree head){
if(head==null){
return;
}
System.out.println(head.value);//先序遍历
orderRecur(head.left);
//System.out.println(head.value);//中序遍历
orderRecur(head.right);
//System.out.println(head.value);//后序遍历
}
2.非递归法实现二叉树的先序遍历、中序遍历、后序遍历
(1)先序遍历,用栈实现
把根节点压入栈;
栈弹出一个节点,并打印值;
压入该节点的左孩子和右孩子;
重复上述过程。
public static void firstOrderRecur(Tree head){
//头左右
if(head!=null){
Stack stack= new Stack<>();
stack.add(head);
Tree cur;
while(!stack.isEmpty()){
cur=stack.pop();
System.out.println(cur.value);
if(cur.right!=null){
stack.add(cur.right);
}
if(cur.left!=null){
stack.add(cur.left);
}
}
}
}
(2)中序遍历:左头右
先把整颗树的左边界进栈,然后依次弹出节点的过程中打印,并对弹出节点的右树重复
public static void midOrderRecur(Tree head){
if(head!=null){
Stack stack=new Stack<>();
while(!stack.isEmpty()||head!=null){
if(head!=null){
stack.add(head);
head=head.left;
}else{
head=stack.pop();
System.out.println(head.value);
head=head.right;
}
}
}
}
(3)后序遍历:左右头
从栈中弹出一个节点,把该节点放入一个收集栈;先把该节点的左孩子压入栈,再把右孩子压入栈;单独打印收集栈
public static void postOrderRecur(Tree head){
if(head!=null){
Stack s1=new Stack<>();
Stack s2=new Stack<>();
s1.add(head);
Tree cur;
while(!s1.isEmpty()){
cur=s1.pop();
s2.add(cur);
if(cur.left!=null){
s1.add(cur.left);
}
if(cur.right!=null){
s1.add(cur.right);
}
}
while(!s2.isEmpty()){
System.out.println(s2.pop().value);
}
}
}
3.宽度优先遍历
深度优先遍历:先序遍历
宽度优先遍历使用队列,弹出即打印,先存左再存右:
public static void widthRecur(Tree head){
if(head!=null){
Queue queue= new LinkedList<>();
queue.add(head);
while(!queue.isEmpty()){
System.out.println(queue.poll().value);
if(head.left!=null){
queue.add(head.left);
}
if(head.right!=null){
queue.add(head.right);
}
}
}
}
4.确定一棵二叉树的最大宽度
在3的基础上添加一个hashmap即可实现对每层节点数的统计。
public static int findMaxWidth(Tree head){
if(head==null){
return 0;
}
Queue queue=new LinkedList<>();
queue.add(head);
HashMap hashmap=new HashMap();
int curlevel=1;
int curlevelNum=0;
int max=Integer.MIN_VALUE;
hashmap.put(head,curlevel);
while(!queue.isEmpty()){
Tree cur=queue.poll();
if(hashmap.get(cur)==curlevel){
curlevelNum++;
}else{
max=Math.max(max,curlevelNum);
curlevel++;
curlevelNum=1;
}
if(cur.left!=null){
queue.add(cur.left);
hashmap.put(cur.left,curlevel+1);
}
if(cur.right!=null){
queue.add(cur.right);
hashmap.put(cur.right,curlevel+1);
}
}
max=Math.max(max,curlevelNum);
return max;
}



