![](/img/trans.png)
[英]Explain how recursion works in an algorithm to determine depth of binary tree?
[英]How to store depth of 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;
};
};
我当时正在考虑创建一个变量,以使其每次从头开始遍历左右分支时都增加一个变量。 但是我意识到这将比较左分支的节点总数与右分支的节点总数,这是行不通的。
首先,找到根的最大深度,然后找到根的最小深度。 使用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))
在每次检查时,为什么要再次发送头,就像为什么再次发根? this.left.checkChild(root)
相反,如果要查找深度,则实现应如下所示:
function treeDepth(tree)
{
if (tree === null)
return 0;
else
{
/* compute the depth of each subtree */
let leftDepth = treeDepth(tree.left);
let rightDepth = treeDepth(tree.right);
/* use the larger one */
if (leftDepth > rightDepth)
return(leftDepth+1);
else return(rightDepth+1);
}
}
如果要将checkChild
用作方法,则应这样定义它,而不是将其定义为变量。 我也建议不要返回布尔值,而是返回左子树和右子树之间深度的真正差异。 这将为调用者提供更多信息,如果愿意,调用者仍可以将该值视为布尔值(虚假表示平衡,真实表示倾斜)。
这是您的实现的外观:
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());
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.