leetcode之判断是否BST二分搜索树

本文介绍了一种通过中序遍历来验证给定二叉树是否为有效的二叉搜索树的方法,避免了递归调用过多导致的时间复杂度过高的问题。

题目:

Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

思路:一种方法是,先判断左侧左子树是否为BST,再判断右子树是否为BST,如果都是,再判断左子树最大的是否小于根节点,右子树最小的是否大于根节点,如果都是,则为合法的BST,具体实现可用递归,可是这种方法的缺陷是递归的次数太多,时间复杂度太大。另一种时间复杂度合理的思路是把这这棵树按照中序遍历打印出来,看看是否从小到大,因为中序遍历从小到大等价于为BST,实现按照递归来做,递归次数合理,时间复杂度不会太大。


代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };                       
 */

struct Node {
    int val;
    Node * next;
    Node(int x) : val(x), next(NULL){}
};

class Solution {
public:
    Node * makeInorderList(TreeNode * root)
    {
        if(root==NULL)
        {
            return NULL;
        }
        if(root->left==NULL && root->right==NULL)
        {
            Node * list= new Node(root->val);
            return list;
        }
        if(root->left!=NULL)
        {
            Node * list=makeInorderList(root->left);
            Node * p=list;
            while(p->next!=NULL)
            {
                p=p->next;
            }
            p->next=new Node(root->val);
            if(root->right!=NULL)
            {
                p=p->next;
                p->next=makeInorderList(root->right);
            }
            return list;
        }else
        {
            Node * list=new Node(root->val);
            if(root->right!=NULL)
            {
                list->next=makeInorderList(root->right);
            }
            return list;
        }
    }
    bool isValidBST(TreeNode *root) {
        if(root==NULL)
        {
            return true;
        }
        Node * list=makeInorderList(root);
        Node * p=list;
        if(p->next==NULL)
        {
            return true;
        }
        Node *q=p->next;
        while(q!=NULL)
        {
            if(p->val>=q->val)
            {
                return false;
            }
            p=p->next;
            q=q->next;
        }
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值