如何存储二进制搜索树的深度

时间:2018-01-20 18:17:15

标签: javascript binary-search-tree

我正在尝试确定二进制搜索树是否平衡。我不太清楚如何存储左右分支的子节点的深度。如果右分支大于左分支的最大长度为1,我试图返回true,反之亦然。

 /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
/**
     * @param {TreeNode} root
     * @return {boolean}
     */

var isBalanced = function(root) {
  var checkChild = function(root) { 
    if (this.left) {
      var left = 1;
      this.left.checkChild(root);
      if (this.right) {
        left += 1;
        this.right.checkChild(root);
      }
      if (this.right) {
        var right = 1;
        this.right.checkChild(root);
        if (this.left) {
          right += 1;
          this.right.checkChild(root);
        }
      }
    }
    if (left - right > 1 || right - left > 1) {
      return false;
    }
    return true;
  };
};

我正在考虑创建一个var,每次从头开始遍历一个节点的右边和左边的分支。但我意识到这将比较左分支的节点总数与右分支上的节点总数,这是行不通的。

3 个答案:

答案 0 :(得分:1)

首先找到根的最大深度,然后找到根的最小深度。使用dfs很容易。下一步是检查这些深度的差异。 代码如下所示:

class Node {
    constructor(value) {
        this.value = value
        this.left = null
        this.right = null
    }
}

var isBalanced = function(root) {
    var foo = function(root, fun) {
        if (root === null) return 0
        l = foo(root.left, fun)
        r = foo(root.right, fun)
        return fun(l, r);
    }
    return foo(root, Math.max) - foo(root, Math.min) < 2
}

let tree = new Node(1)
tree.left = new Node(2)
tree.left.left = new Node(3)
tree.left.left.left = new Node(4)
tree.right = new Node(5)
tree.right.left = new Node(6)
document.write(isBalanced(tree))

答案 1 :(得分:1)

在每次检查时你为什么要再次发送头像 为什么再次root? <body onload="onload()">

相反,如果你想找到深度,你的实现应该是这样的:

this.left.checkChild(root)

答案 2 :(得分:1)

如果要将checkChild用作方法,则应将其定义为此类,而不是变量。我还建议不要返回布尔值,但左右子树之间的深度真正不同。这将为调用者提供更多信息,如果需要,调用者仍然可以将该值视为布尔值(falsy表示平衡,truthy意味着倾斜)。

以下是您的实施方式:

&#13;
&#13;
class TreeNode {
    constructor(val) {
        this.val = val;
    }
    add(node) {
        const dir = node.val < this.val ? "left" : "right";
        if (this[dir]) {
            this[dir].add(node);
        } else {
            this[dir] = node;
        }
    }
    height() {
        return Math.max(
            this.left ? this.left.height() + 1 : 0,
            this.right ? this.right.height() + 1 : 0
        );
    }
    tilt() {
        return (this.left  ? this.left.height() + 1 : 0)
             - (this.right ? this.right.height() + 1 : 0);
    }
    static from(...data) {
        if (!data.length) return;
        const root = new TreeNode(data[0]);
        for (let v of data.slice(1)) {
            root.add(new TreeNode(v));
        }
        return root;
    }
}

const root = TreeNode.from(13, 4, 9, 16);
console.log(root);
console.log('Tilt at root = ', root.tilt());
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;