【算法与数据结构】98、LeetCode验证二叉搜索树

文章目录

  • 一、题目
  • 二、解法
  • 三、完整代码

所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。

一、题目

【算法与数据结构】98、LeetCode验证二叉搜索树_第1张图片
【算法与数据结构】98、LeetCode验证二叉搜索树_第2张图片

二、解法

  思路分析:注意不要落入下面你的陷阱,笔者本来想左节点键值<中间节点键值<右节点键值即可,写出如下代码:

class Solution2 {
public:
    // 1、输入参数, 返回值为result,以引用方式传入
    void traversal_preOrder(TreeNode* cur, bool &result) {
        // 2、终止条件
        if (cur == NULL) return;
        if (cur->left && cur->left->val >= cur->val) result = 0;
        if (cur->right && cur->right->val <= cur->val) result = 0;

        // 3、单层递归逻辑
        if (result) traversal_preOrder(cur->left, result);     // 左
        if (result) traversal_preOrder(cur->right, result);    // 右
    }
    bool isValidBST(TreeNode* root) {
        bool result = 1;
        traversal_preOrder(root, result);
        return result;
    }
};

  在leetcode执行时遇到下面的错误,再次读题,发现是所有左子树的键值小于中间节点键值,所有右子树键值大于中间节点键值,这个性质和中序遍历有所关联。如此一来,我们就想到用中序遍历来做,中序遍历数组是一个有序数组,判断该数组是否有序即可
【算法与数据结构】98、LeetCode验证二叉搜索树_第3张图片

  程序如下

class Solution {
public:
    void traversal_midOrder(TreeNode* cur, vector<int>& vec) {
        if (cur == NULL) return;
        traversal_midOrder(cur->left, vec);     // 左
        vec.push_back(cur->val);                // 中
        traversal_midOrder(cur->right, vec);    // 右
    }

    bool isValidBST(TreeNode* root) {
        if (root == NULL) return {};
        vector<int> v;
        traversal_midOrder(root, v);
        for (int i = 0; i < v.size()-1; i++) {
            if (v[i] >= v[i + 1]) return false;
        }
        return true;
    }
};

三、完整代码

# include 
# include 
# include 
# include 
using namespace std;

// 树节点定义
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    void traversal_midOrder(TreeNode* cur, vector<int>& vec) {
        if (cur == NULL) return;
        traversal_midOrder(cur->left, vec);     // 左
        vec.push_back(cur->val);                // 中
        traversal_midOrder(cur->right, vec);    // 右
    }

    bool isValidBST(TreeNode* root) {
        if (root == NULL) return {};
        vector<int> v;
        traversal_midOrder(root, v);
        for (int i = 0; i < v.size()-1; i++) {
            if (v[i] >= v[i + 1]) return false;
        }
        return true;
    }
};

class Solution2 {
public:
    // 1、输入参数, 返回值为result,以引用方式传入
    void traversal_preOrder(TreeNode* cur, bool &result) {
        // 2、终止条件
        if (cur == NULL) return;
        if (cur->left && cur->left->val >= cur->val) result = 0;
        if (cur->right && cur->right->val <= cur->val) result = 0;

        // 3、单层递归逻辑
        if (result) traversal_preOrder(cur->left, result);     // 左
        if (result) traversal_preOrder(cur->right, result);    // 右
    }
    bool isValidBST(TreeNode* root) {
        bool result = 1;
        traversal_preOrder(root, result);
        return result;
    }
};

// 前序遍历迭代法创建二叉树,每次迭代将容器首元素弹出(弹出代码还可以再优化)
void Tree_Generator(vector<string>& t, TreeNode*& node) {
    if (!t.size() || t[0] == "NULL") return;    // 退出条件
    else {
        node = new TreeNode(stoi(t[0].c_str()));    // 中
        if (t.size()) {
            t.assign(t.begin() + 1, t.end());
            Tree_Generator(t, node->left);              // 左
        }
        if (t.size()) {
            t.assign(t.begin() + 1, t.end());
            Tree_Generator(t, node->right);             // 右
        }
    }
}

template<typename T>
void my_print(T& v, const string msg)
{
    cout << msg << endl;
    for (class T::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << ' ';
    }
    cout << endl;
}

template<class T1, class T2>
void my_print2(T1& v, const string str) {
    cout << str << endl;
    for (class T1::iterator vit = v.begin(); vit < v.end(); ++vit) {
        for (class T2::iterator it = (*vit).begin(); it < (*vit).end(); ++it) {
            cout << *it << ' ';
        }
        cout << endl;
    }
}

// 层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
    queue<TreeNode*> que;
    if (root != NULL) que.push(root);
    vector<vector<int>> result;
    while (!que.empty()) {
        int size = que.size();  // size必须固定, que.size()是不断变化的
        vector<int> vec;
        for (int i = 0; i < size; ++i) {
            TreeNode* node = que.front();
            que.pop();
            vec.push_back(node->val);
            if (node->left) que.push(node->left);
            if (node->right) que.push(node->right);
        }
        result.push_back(vec);
    }
    return result;
}

int main()
{
    vector<string> t = { "5", "4", "NULL", "NULL", "6", "3", "NULL", "NULL", "7", "NULL", "NULL" };   // 前序遍历
    my_print(t, "目标树");
    TreeNode* root = new TreeNode();
    Tree_Generator(t, root);
    vector<vector<int>> tree = levelOrder(root);
    my_print2<vector<vector<int>>, vector<int>>(tree, "目标树:");

    Solution s;
    bool result = s.isValidBST(root);
    if (result) cout << "是一棵二叉搜索树" << endl;
    else cout << "不是一棵二叉搜索树" << endl;

	system("pause");
	return 0;
}

end

你可能感兴趣的:(算法,算法)