使用顺序检查树是否是二叉搜索树

时间:2018-06-27 15:11:06

标签: c++ arrays sorting binary-search-tree

int* inorder(node* root)
{
    //Dynamically Created array as we are required to pass array into main function
    int* arr=new int[100];
    int i=0;
    if(root==NULL)
    return 0;
    inorder(root->left);
    arr[i]=root->data;
    i++;
    inorder(root->right);
    return arr;
}

我们需要使用Inorder遍历检查树是否为Bst。如果数组中存在的数据已排序,则为Bst。在main()中传递数组后,我们将检查数组是否已排序或不是,但当我检查数组的内容时,它显示为垃圾值 并且对于输入树bst来说,tree总是不是Bst

int main()
{
    node* root= newNode(6);
    root->left= newNode(4);
    root->right= newNode(8);
    root->left->left= newNode(3);
    root->left->right= newNode(5);
    root->right->left= newNode(7);
    root->right->right= newNode(9);
    int* ptr=inorder(root);
    if(is_sorted(ptr,ptr+7))
    cout<<"Tree is Binary search tree: "<<endl;
    else
    cout<<"Tree is not a binary search tree: "<<endl;
}

1 个答案:

答案 0 :(得分:0)

此处无需使用向量。确定一棵树是否为二叉搜索树,除了用于递归调用的堆栈外,不需要任何额外的内存。

如果您定义了一个单独的有序树遍历算法,则该实现几乎是微不足道的:

OverloadedStrings

要使用有序遍历将树转换为向量,可以使用以下函数:

#include <utility>
#include <functional>

template<class T>
struct Node {
    T value;
    Node *left, *right;
};

template<class T, class F>
bool traverse_inorder(Node<T> const* tree, F&& f) {
    return !tree || (
           traverse_inorder(tree->left, std::forward<F>(f))
        && f(tree->value)
        && traverse_inorder(tree->right, std::forward<F>(f))
        );
}

template<class T, class Pred>
bool is_bst(Node<T> const* tree, Pred&& pred) {
    T const* p = 0;
    return traverse_inorder(tree, [&p, &pred](T const& next) {
        T const* prev = p;
        p = &next;
        return !prev || !pred(next, *prev);
    });
}

template<class T>
bool is_bst(Node<T> const* tree) {
    return is_bst(tree, std::less<T>{});
}

int main() {
    // bst tree:
    //       33
    //   20      35
    // 10  30
    Node<int> n1{10}, n3{30}, n2{20, &n1, &n3}, n5{35}, n4{33, &n2, &n5};
    auto tree = &n4;

    std::cout << is_bst(tree) << '\n'; // Outputs 1.

    // Break bst property.
    n4.value = 25;
    std::cout << is_bst(tree) << '\n'; // Outputs 0.
}
相关问题