Skip to content

获取树的高度

通过递归获取

javascript
function height(root) {
  if (root === null) {
    return 0;
  } else {
    const lHeight = height(root.left);
    const rHeight = height(root.right);
    if (lHeight > rHeight) {
      return lHeight + 1;
    } else {
      return rHeight + 1;
    }
  }
}

Test Cases

javascript
const { height } = require('../docs/algo/tree/height');
const { generateTree } = require('../docs/algo/common/generator');

describe('getTreeHeight', () => {
  it('null', () => {
    const tree = null;
    expect(height(tree)).toBe(0);
  });
  it('Is not empty tree', () => {
    /* Constructed binary tree is
                    1
                  /   \
                2      3
              /  \
            4     5
    */
    const root = generateTree();
    expect(height(root)).toBe(3);
  });
});
shell
# /test/height.test.js
jest --testNamePattern=height