给定的二叉树是否是有效的BST?

时间:2019-06-12 05:29:50

标签: c++ data-structures tree binary-search-tree

如果树是BST。那么顺序遍历必须给我们一个排序后的数组。 如果数组已排序,则给定的树必须是BST 那么这段代码为什么会失败

非常感谢

void getInorder(vector<int> &inorder, TreeNode* A){

    if(A == NULL)
        return;
    getInorder(inorder,A->left);
    //cout<<A->val<<" ";
    inorder.push_back(A->val);
    getInorder(inorder,A->right);
}

int Solution::isValidBST(TreeNode* A) {
    //If it is a valid BST //Then its inorder Must be a sorted array;
    vector<int> inorder;

    if(A == NULL)
        return 0;

    getInorder(inorder,A);

    // for(int a:inorder)
    //     cout<<a<<" ";

    cout<<endl;
    return is_sorted(inorder.begin(), inorder.end()) == true ? 1 : 0;
}

输出 1:是BST, 0:不是BST

Failing Test Case :

     2
   /   \
  1     2

其有序遍历为:1,2,2(已排序) MyCode O / P:1,预期O:P:0

原因:(它不是BST,因为Right Sub树 必须具有大于Root的值,在这种情况下,该值等于root)

如果以某种顺序出现,则无法获得重复的值。

1 个答案:

答案 0 :(得分:0)

问题在于 workbook.LoadFromFile("test.xls"); Worksheet sheet = workbook.Worksheets[0]; sheet.Unprotect( "password" ); workbook.SaveToFile("result.xls",ExcelVersion.Version97to2003) 实际上是一个排序列表。因此,{1, 2, 2}对这样的数组返回true。这是一个供您尝试的小示例:

std::is_sorted

输出为#include <iostream> #include <string> #include <vector> #include <algorithm> int main() { std::vector<int> mtmd = {1, 2, 3, 4, 5, 5}; std::cout << std::is_sorted(mtmd.begin(), mtmd.end()) << std::endl; } ,应该是。最好的解决方案是实施自己的true

相关问题