1.判断每层的最左最右节点
2.构建一个二维数组装左右节点
3.打印左边界
4.打印非边界的叶子节点
5.打印右边界
public class Code_02PrintEdgel {
public class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
public void printEdgel(Node head){
if(head == null){
return;
}
int height = getHeight(head, 0);
Node[][] edgeMap = new Node[height][2];
setEdgeMap(head, 0, edgeMap);
//打印左边界
for (int i = 0; i != edgeMap.length; i++) {
System.out.println(edgeMap[i][0].value + " ");
}
//打印非左右边界的叶子节点
printLeafNotInMap(head, 0, edgeMap);
//打印右边界,但不是左边界的节点
for (int i = edgeMap.length - 1; i != -1 ; i--) {
if(edgeMap[i][0]!=edgeMap[i][1]){
System.out.println(edgeMap[i][1].value + " ");
}
}
System.out.println();
}
//得到二叉树的高度
public int getHeight(Node h,int l){
//递归到节点为空的时候返回高度
if(h == null){
return l;
}
return Math.max(getHeight(h.left, l+1),getHeight(h.right, l+1));
}
//给二维数组赋值
public void setEdgeMap(Node h,int x,Node[][]edgeMap){
if(h == null){
return;
}
edgeMap[x][0] = edgeMap[x][0] == null ? h:edgeMap[x][0];
edgeMap[x][1] = h;
setEdgeMap(h.left, x + x, edgeMap);
setEdgeMap(h.right, x + 1 , edgeMap);
}
//打印非左右边界的叶子节点
public void printLeafNotInMap(Node h,int x,Node[][] m){
if(h == null){
return;
}
if(h.left == null&&h.right==null&&h!=m[x][0]&&h!=m[x][x]){
System.out.println(h.value + " ");
}
printLeafNotInMap(h.left, x + 1, m);
printLeafNotInMap(h.right, x + 1, m);
}
}