如何用更少的行编写这段 JavaScript 代码来查找一棵树是否是二叉搜索树?

2023-12-20

在我的 Javascript 类测验中,我们被告知要制作一个简单的树并编写一个返回 true 或 false 的函数,无论它是否是 BST。

我的成绩还不错,但是我被扣了10分,因为老师说“可以少6行就完成”。

这就是我所拥有的:

function node(value, left, right){
    this.Value = value;
    this.Left = left;
    this.Right = right;
}

//this IS a BST, returns true
var head = new node(8, new node(9, null, null), new node(10, new node(9, null, null), new node(14, new node(13, null, null), null)));


function isBST(currNode){
    if(currNode.Left === null && currNode.Right === null){
        return true;
    }
    else if(currNode.Left.Value > currNode.Value || currNode.Right.Value < currNode.Value){
        return false;
    }
    else{
        if(currNode.Left === null){
            return isBST(currNode.Right);
        }
        else if(currNode.Right === null){
            return isBST(currNode.Left);
        }
        else{
            return (isBST(currNode.Left) && isBST(currNode.Right));
        }
    }
}


console.log(isBST(head));

我在这里忽略了什么吗?也许它不应该是递归的?


您当前的功能的问题是它不起作用。它返回 true:

     4
    / \
   3   5
  / \
 2  100

看来此时所有其他答案都有同样的问题。这是一个有效且短得多的方法

function isBST(curNode, minval, maxval){
    if (curNode == null) {
        return true;
    }
    return (
        (minval == null || minval <= curNode.Value) &&
        (maxval == null || maxval >= curNode.Value) &&
        isBST(curNode.Left, minval, curNode.Value) &&
        isBST(curNode.Right, curNode.Value, maxval)
    );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用更少的行编写这段 JavaScript 代码来查找一棵树是否是二叉搜索树? 的相关文章

随机推荐