2021-05-16

static TreeNode<Integer> t1;

    static int leftDepth = 1;
    static int rightDepth = 1;

    public static void main(final String[] args) throws Exception {

        initData();

        int depth = caculateDepth(t1);
        System.out.println(depth+"");
    }

    private static void initData() {
        //1.父
        t1 = new TreeNode<>(154);

        //2.父 左
        t1.addLeft(254);

        //父 左 左, 父 左 右
        t1.leftChild.addLeft(97);
        t1.leftChild.addRight(101);

        //父 左 右 左
        t1.leftChild.rightChild.addLeft(66);

        //父 左 右 左 左, 父 左 右 左 右
        t1.leftChild.rightChild.leftChild.addLeft(33);
        t1.leftChild.rightChild.leftChild.addRight(100);

        //3.父 右
        t1.addRight(354);

        //父 右 左
        t1.rightChild.addLeft(88);
    }

    private static int caculateDepth(TreeNode t) {

        int depth = 0;

        if (t != null) {
            int leftDepth = caculateDepth(t.leftChild);
            int rightDepth = caculateDepth(t.rightChild);

            //从第一个解析,左边最大长度和右边最大长度,肯定取更长的+1
            depth = leftDepth >= rightDepth ? leftDepth + 1 : rightDepth + 1;
        }

        return depth;
    }
}

class TreeNode<T> {

    T value;

    TreeNode<T> leftChild;
    TreeNode<T> rightChild;

    TreeNode(T value) {
        this.value = value;
    }
    TreeNode() {
    }

    public void addLeft(T value){
        TreeNode<T> leftChild = new TreeNode<T>(value);
        this.leftChild = leftChild;
    }

    public void addRight(T value){
        TreeNode<T> rightChild = new TreeNode<T>(value);
        this.rightChild = rightChild;
    }

    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        if(!(obj instanceof TreeNode)){
            return false;
        }
        return this.value.equals(((TreeNode<?>)obj).value);
    }

    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return this.value.hashCode();
    }

    @Override
    public String toString(){
        return this.value==null?"":this.value.toString();
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2021反思日记,5月周末。16号,年怕过半,月也怕过半,这个月几乎快完了,时间真的是过的很快的。人生的意义到底在...
    因悦盒阅读 173评论 0 0
  • 还是喜欢花
    王晴天阅读 85评论 0 0
  • 侯雨去参加公司聚会。因为没车,早早地去了城里,本以为可以慢慢步行过去,结果时间快到了才发现自己走错了。眼看要迟到,...
    龙走走阅读 109评论 0 1
  • 今天青石的票圈出镜率最高的,莫过于张艺谋的新片终于定档了。 一张满溢着水墨风的海报一次次的出现在票圈里,也就是老谋...
    青石电影阅读 10,475评论 1 2
  • 今天主要学习了flex布局,学习笔记如下: 1.指定flex布局: display:flex(任意容器)...
    riku_lu阅读 3,187评论 2 3