打印二叉树的边界节点

详情如图

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);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值