二叉树的层序遍历算法 + 打印二叉树所有最左边的元素(算法)
层序遍历
/**
* 树结构定义
*/
private static class BinaryNode<T> {
BinaryNode(T theElement) {
this(theElement, null, null);
}
BinaryNode(T theElement, BinaryNode<T> lt, BinaryNode<T> rt) {
element = theElement;
left = lt;
right = rt;
}
T element;
BinaryNode<T> left;
BinaryNode<T> right;
}
//层序遍历方法
public static void levelRead(BinaryNode node) {
if (node == null) {
return;
}
//计算深度
int depth = calcDepth(node);
for (int i = 0; i < depth; i++) {
//打印每个深度上的所有节点
readLevel(node,i);
}
}
private static void readLevel(BinaryNode node, int i) {
if (node =