Java 二叉树高度的实现

Java 二叉树高度的实现,java,height,binary-tree,implementation,Java,Height,Binary Tree,Implementation,这是我在互联网上发现的最常见的二叉树高度实现 public int height(BinaryNode t) { if (t == null) { return 0; } else { return 1 + Math.max(height(t.left), height(t.right)); } } 但它不应该这样修改吗,因为它在叶节点添加了一个不必要的1 public int heigh

这是我在互联网上发现的最常见的二叉树高度实现

public int height(BinaryNode t) {
        if (t == null) {
            return 0;
        } else {
            return 1 + Math.max(height(t.left), height(t.right));

        }
    }
但它不应该这样修改吗,因为它在叶节点添加了一个不必要的1

public int height(BinaryNode t) {
        if (t == null) {
            return 0;
        } else if (t.left == null && t.right == null) {
            return 0;
        } else {
            return 1 + Math.max(height(t.left), height(t.right));
        }
    }

不,想象一下最简单的情况:一棵树的根也是唯一的叶子。你会得到多高?包含单个节点的树的高度是0,对吗?它只取决于你所称的高度。但正如Ben所说,一个节点的高度为1,一个父母和两个孩子的高度为2,等等……这确实是正确的。我没有正确阅读你的代码。对于这种情况,大多数常见的实现都有一个
if(t==null)返回-1