算法设计与应用基础: 第七周(1)

来源:互联网 发布:什么变声软件好用 编辑:程序博客网 时间:2024/06/10 00:36

98. Validate Binary Search Tree

DescriptionSubmissionsSolutions
  • Total Accepted: 151797
  • Total Submissions: 665772
  • Difficulty: Medium
  • Contributor: LeetCode

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.

解题思路:一开始想到的是中序遍历,然后将遍历到所有节点的val值压到vector中,最后对vector进行遍历判断是否为严格升序,但是这个方法实现起来太复杂(或者说是太不优美),于是继续想了想应该用递归可以直接判断,这里有一个难点是如何判断子节点与祖父节点之间的大小(也就是所谓的伪BST树),这里用的办法是新使用一个函数judge(新加参数min,max来保存祖父节点的val值)。

class Solution {public:    bool isValidBST(TreeNode* root) {         return Judge(root, -2147483648, 2147483647);                 }    bool Judge(TreeNode* root,int min,int max)    {        if(root==NULL)            return true;        if(root->val < min || root->val > max){            return false;        }        else if(root->left&&root->right)        {            //cout<<1<<endl;            if(root->left->val < root->val && root->right->val > root->val){                return Judge(root->left, min, root->val-1) && Judge(root->right, root->val+1, max);            }else{                return false;            }        }        else if(root->left!=NULL)        {            //cout<<2<<endl;            return (root->val>root->left->val)&&Judge(root->left,min,root->val-1);        }        else if(root->right!=NULL)        {            //cout<<3<<endl;            return(root->val<root->right->val)&&Judge(root->right,root->val+1,max);        }        else            return true;    }};

0 0
原创粉丝点击