2021-05-16

static TreeNode 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 value;

    TreeNode leftChild;
    TreeNode rightChild;

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

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

    public void addRight(T value){
        TreeNode rightChild = new TreeNode(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-05-16)