Java实现深度优先遍历和广度优先遍历
程序员文章站
2022-05-22 20:26:42
...
深度优先遍历
public static void depthterator(BiTree root){
if(root == null){
return;
}
Stack<BiTree> stack = new Stack<>(); //深度遍历,利用栈后进先出的特性
stack.push(root);
while(!stack.isEmpty()){
BiTree current = stack.pop();
System.out.println("--->" + current.val);
if(current.right != null){
stack.push(current.right); //右子树入栈
}
if(current.left != null){
stack.push(current.left); //左子树入栈
}
}
}
广度优先遍历(层次遍历)
public static void levelIterator(BiTree root){
if(root == null){
return;
}
LinkedList<BiTree> queue = new LinkedList<>(); //广度遍历,利用队列先进先出的特性
queue.offer(root);
while(!queue.isEmpty()){
BiTree current = queue.poll();
System.out.println("--->" + current.val);
if(current.left != null){
queue.offer(current.left); //左子树入队
}
if(current.right != null){
queue.offer(current.right); //右子树入队
}
}
}