一、二叉树宽度优先遍历和求二叉树宽度
public class bfsTree{
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
public static void bfs(Node head){
if(head == null){
return;
}
Queue<Node> queue = new LinkerList<>();
queue.add(head);
while(!queue.isEmpty()){
Node cur = queue.poll();
System.out.println(cur.value);
if(cur.left != null){
queue.add(cur.left);
}
if(cur.right != null){
queue.add(cur.right);
}
}
}
public static int W(Node head){
if(head == null){
return 0;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
HashMap<Node,Integer> levelMap = new HashMap<>();
levelMap.put(head,1);
int curLevel = 1;
int curLevelNodes = 0;
int max = Integer.MIN_VALUE;
while(!queue.isEmpty()){
Node cur = queue.poll();
int curNodeLevel = levelMap.get(cur);
if(curNodeLevel == curLevel){
curLevelNodes++;
}else{
max = Math.max(max,curLevelNodes);
curLevel++;
curLevelNodes = 1;
}
if(cur.left != null){
levelMap.put(cur.left,curLevel+1);
queue.add(cur.left);
if(cur.right != null){
levelMap.put(cur.right,curLevel+1);
queue.add(cur.right);
}
}
return max;
}
}
二、判断一棵树是否是搜索二叉树
public class CheckBST {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data