一棵树的高度

时间:2018-02-19 14:27:33

标签: java recursion

我有2个树的高度实现:

public int height() {
    if (isEmpty()) {
        return 0;
    } else {
        return 1 + Math.max(leftChild.height(), rightChild.height());
    }
}

和:

public int height2() {
    if (!isEmpty()) {
        int leftHeight = leftChild.height2();
        int rightHeight = rightChild.height2();
        if (leftHeight > rightHeight) {
            return leftHeight + 1;
        } else {
            return rightHeight + 1;
        }
    } else {
        return 0;

    }
}

两者都有效,但我不理解第二个。他如何比较 leftHeight>如果他们之前从未得到过数字,那么他们是不是很好?

谢谢!

1 个答案:

答案 0 :(得分:3)

在这两个例子中,逻辑是:

  1. 如果节点为空,则返回0
  2. 如果节点不为空:
    1. 获取leftChild节点的高度(递归)
    2. 获取rightChild节点的高度(递归)
    3. 一旦我们有了这些,比较它们来决定哪个更大
    4. 返回大一加一
  3. 第二个示例使用比较来简单地执行Math.max,而不是将值传递给Math.max。当 函数获得leftChildrightChild的高度时,没有区别。

    我建议在调试器中逐步执行code-by-statement,以查看递归发生的时间以及值何时可用。

    以下是JavaScript中的一个示例(语言在这里并不重要,这是关于递归),这可能会使它更清晰:

    let indent = "";
    class TreeNode {
      constructor(name, leftChild = null, rightChild = null) {
        this.name = name;
        this.leftChild = leftChild;
        this.rightChild = rightChild;
      }
      isEmpty() {
        return this.leftChild == null && this.rightChild == null;
      }
      height2() {
        indent = "  " + indent;
        console.log(indent + "Getting height of " + this.name);
        try {
          if (!this.isEmpty()) {
              let leftHeight = this.leftChild.height2();
              let rightHeight = this.rightChild.height2();
              if (leftHeight > rightHeight) {
                  console.log(indent + "Done, height of " + this.name + " is " + (leftHeight + 1));
                  return leftHeight + 1;
              } else {
                  console.log(indent + "Done, height of " + this.name + " is " + (rightHeight + 1));
                  return rightHeight + 1;
              }
          } else {
              console.log(indent + "Done, height of " + this.name + " is 0");
              return 0;
          }
        } finally {
          indent = indent.substring(2);
        }
      }
    }
    const t = new TreeNode(
      "top",
      new TreeNode(
        "middle-left",
        new TreeNode("bottom-left-left"),
        new TreeNode("bottom-left-right")
      ),
      new TreeNode(
        "middle-right",
        new TreeNode("bottom-right-left"),
        new TreeNode("bottom-right-right")
      )
    );
    console.log(t.height2());
    .as-console-wrapper {
      max-height: 100% !important;
    }