检查树是否为BST

时间:2016-11-29 15:30:43

标签: ruby binary-search-tree

我在ruby中编写了一个代码来检查传入的树是否是二叉搜索树。只是想检查我是否在正确的轨道上。

def checkBST(t) 
    return false if t==nil
   if t.left!=nil && t.left>t 
        return false
    end
    if t.right!=nil && t.right<t
        return false
    end
    if checkBST(t.left) && checkBST(t.right)
        return true
    end
end

1 个答案:

答案 0 :(得分:0)

让我先逐行解释: -

1    def checkBST(t) 
2        return false if t==nil
3       if t.left!=nil && t.left>t 
4            return false
5        end
6        if t.right!=nil && t.right<t
7            return false
8        end
9        if checkBST(t.left) && checkBST(t.right)
10            return true
11        end
12    end

第2行 - 当t为NULL时返回true。

第3行和第6行 - 你正在检查直系孩子,如果孩子满足BST财产但不满足其子女,该怎么办?试试自己,你会知道我想说的是什么。

这是一个可能的解决方案 - 我只是编写它,没有编译,你可以更多地工作。

功能 -

bool isBST(class tree* root, int minL, int maxR)
{
    if(!root)
        return true;
    else if(root->data > minL && root->data < maxR)
        return true;
    else if(root->data < minL || root->data > maxR)
        return false;
    return isBST(root->right, root->data, maxR) && isBST(root->left, minL, root->data);
}

Caller - 
isBST(root, INT_MIN, INT_MAX);
相关问题