import java.util.ArrayList;
import java.util.List;
/**
*
* 分层遍历二叉树
*
* 分层次遍历上面的树并且可以直接输出 i 层的元素(层次从0开始) 5
*/ // 3 8
public class ListTreeByLevel { // 2 4 6 9
private Entry root;
public ListTreeByLevel add(int val) {
Entry entry = new Entry(val, null, null);
if (root == null) {
root = entry;
return this;
}
Entry p = root, parent = p;
while (p != null) {
int cmp = val < p.val ? -1 : (val > p.val ? 1 : 0);
parent = p;
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return this;
}
if (val < parent.val)
parent.left = entry;
else
parent.right = entry;
return this;
}
public void list() {
preList(root);
}
// 先序
private void preList(Entry e) {
if (e == null)
return;
preList(e.left);
System.out.println(e.val);
preList(e.right);
}
/**
*
* 遍历 第 i 层的 所有元素,想遍历i 层,我们就得知道 i-1 层的所有元素 当层次为 0 时,就可以直接输出的 所以,递归
* list(e.left,i-1) list(e.right,i-1)
*/
public void listLevelHelper(Entry e, int i) {
if (e == null || i < 0)
return;
if (i == 0)
System.out.print(e.val + " ");
listLevelHelper(e.left, i - 1);
listLevelHelper(e.right, i - 1);
}
public void listLevel(int level) {
listLevelHelper(root, level);
}
/**st
可以以上面的方法进行全部的元素的遍历,可以求出它的高度,但这种方法每次都要从 根开始遍历,有点慢,我们
可以模仿图的BFS
定义一个数组,每遍历一层 ,用 cursor 指向这一层最开始的位置,last 指向这一层最后一个位置,然后 对[cursort last] 进行求子节点,然后添加到 数组中,
遍历到 last 到,再更新 last 为数组的最后一个元素
*
*/
public void listAll(){
int cursor=0,last=0;
Entry[]array = new Entry[100]; //相当于一个队列
if(root!=null) {
array[0] = root;
last = 1;
}
while(cursor<last){
int t = last;
for(;cursor<last;cursor++){ //此循环为遍历出当前层次的所有结点
Entry e = array[cursor];
System.out.print(e.val+" ");
if(e.left!=null)array[t++] = e.left;
if(e.right!=null)array[t++] = e.right;
}
System.out.println();
last = t;
}
}
static class Entry {
int val;
Entry left;
Entry right;
public Entry(int val, Entry left, Entry right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static void main(String args[]) {
ListTreeByLevel tree = new ListTreeByLevel();
tree.add(5).add(3).add(8).add(2).add(4).add(6).add(9);
tree.listAll();
}
}
编程之美--分层次遍历二叉树
最新推荐文章于 2021-06-25 21:11:12 发布