链表存储——二叉树(Java)

package com.answer.binaryTree;

public class TwoLinkBinTree {
    private static class Node{
        private String data;
        private Node left;
        private Node right;
        public Node(){};
        public Node(String data){
            this.data=data;
        }
        public Node(String data,Node left,Node right){
            this.data=data;
            this.left=left;
            this.right=right;
        }
    }
    private Node root;
    public TwoLinkBinTree(){
        this.root=new Node();
    }
    public TwoLinkBinTree(String data){
        this.root=new Node(data);
    }
    public void add(Node parent,String data,boolean left){
        if(parent==null){
            throw new RuntimeException("父节点为空");
        }
        if(left&&parent.left!=null){
            throw new RuntimeException("已有左节点");
        }
        if(!left&&parent.right!=null){
            throw new RuntimeException("已有右节点");
        }
        Node node=new Node(data);
        if(left){
            parent.left=node;
        }else {
            parent.right=node;
        }
    }
    public boolean empty(){
        return root==null;
    }
    public Node getRoot(){
        if(root==null){
            throw new RuntimeException("没有根节点");
        }
        return root;
    }
    public Node getLeft(Node parent){
        if(parent==null){
            throw new RuntimeException("父节点为空");
        }
        return parent.left==null?null:parent.left;
    }
    public Node getRight(Node parent){
        if(parent==null){
            throw new RuntimeException("父节点为空");
        }
        return parent.right==null?null:parent.right;
    }
    public int deep(){
        return deep(this.root);
    }

    private int deep(Node node) {
        if(node==null){
            return 0;
        }
        if(node.left==null&&node.right==null){
            return 1;
        }else {
            int leftDeep=deep(node.left);
            int rightDeep=deep(node.right);
            int max=leftDeep>rightDeep?leftDeep:rightDeep;
            return max+1;
        }
    }

    public static void main(String[] args) {
        TwoLinkBinTree tree=new TwoLinkBinTree("Root");
        Node root=tree.getRoot();
        tree.add(root,"A",true);
        tree.add(root,"B",false);
        System.out.println(tree.deep());
        System.out.println(tree.getLeft(root).data);
        System.out.println(tree.getRight(root).data);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream答案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值