获得普通二叉树的深度 的两种写法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Yonggie/article/details/89843797

考。自己一直用的第一种,原来还有第二种……还是我太弱鸡……

第一种:

 int Height(TreeNode root,int depth){
        if(root==null) return depth;
        return Math.max(Height(root.left,depth+1),Height(root.right,depth+1));
    }

很显然的啦,每次传入深度,下一层就深度加一。

可以不用depth这个变量的!可以从叶子就1+,回到上层就是深度了!!

这个默认的是一个节点的时候深度是1。

第二种:

int Height(TreeNode root){
        if(root==null) return 0;
        return 1+Math.max(Height(root.left),Height(root.right));
    }

猜你喜欢

转载自blog.csdn.net/Yonggie/article/details/89843797