二叉搜索树——搜索、插入、验证

二叉搜索树——所有节点满足:左<根<右。

节点定义:

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) {}
};
View Code

搜索:

class Solution
{
public:
    TreeNode *searchBST(TreeNode *root, int val)
    {
        if (!root || val == root->val)
            return root;
        return (val > root->val) ? searchBST(root->right, val) : searchBST(root->left, val);
    }
};
搜索

插入:

【有多种插入方式,此为一种】

class Solution
{
public:
    TreeNode *insertIntoBST(TreeNode *root, int val)
    {
        if (root == nullptr)
            return new TreeNode(val);
        TreeNode *n = root;
        while (n != nullptr)
        {
            if (n->val > val)
            {
                if (n->left == nullptr)
                {
                    n->left = new TreeNode(val);
                    break;
                }
                else
                    n = n->left;
            }
            else
            {
                if (n->right == nullptr)
                {
                    n->right = new TreeNode(val);
                    break;
                }
                else
                    n = n->right;
            }
        }
        return root;
    }
};
插入

验证:

【也就是中序遍历为升序】

  迭代法:

class Solution
{
public:
    bool isValidBST(TreeNode *root)
    {
        if (!root)
            return true;
        TreeNode *n = root, *x = nullptr;
        stack<TreeNode *> st;
        while (st.size() || n)
        {
            while (n)
            {
                st.push(n);
                n = n->left;
            }
            if (x && x->val >= st.top()->val)
                return false;
            x = st.top();
            n = st.top()->right;
            st.pop();
        }
        return true;
    }
};
迭代

  递归法:

class Solution
{
public:
    TreeNode *pre = nullptr;
    bool isValidBST(TreeNode *root)
    {
        if (!root)
            return true;
        bool l = isValidBST(root->left);
        if (pre && pre->val >= root->val)
            return false;
        pre = root;
        bool r = isValidBST(root->right);
        return l & r;
    }
};
递归

 

 

posted @ 2022-02-28 18:06  Renhr  阅读(5)  评论(0)    收藏  举报