需要牢记BST的定义:左边的所有节点都小于根节点,根节点小于右边的所有节点
所以这样的做法是错误的:
而正确的做法应该是中序遍历,查看输出是不是有序的
还有一种更直观的
阅读(42) | 评论(0) | 转发(0) |
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
所以这样的做法是错误的:
- bool isValidBST(TreeNode *root) {
- if(root==NULL)
- return true;
- bool l=true;
- bool r=true;
- if(root->left!=NULL)
- l=root->val>root->left->val;
- if(root->right!=NULL)
- r=root->val<root->right->val;
- return l&&r&&isValidBST(root->left)&&isValidBST(root->right);
- }
- TreeNode * pre=NULL;
- bool isValidBST(TreeNode *root) {
- if(root==NULL)
- return true;
- bool l=isValidBST(root->left);
- if(pre==NULL)
- pre=root;
- else{
- if(root->val<=pre->val){
- return false;
- }
- pre=root;
- }
- bool r=isValidBST(root->right);
- return l&&r;
- }
- TreeNode * pre=NULL;
- bool flag=true;
- void f(TreeNode *root) {
- if(root==NULL)
- return;
- f(root->left);
- if(pre==NULL)
- pre=root;
- else{
- if(root->val<=pre->val){
- flag=false;
- return;
- }
- pre=root;
- }
- f(root->right);
- return;
- }
- bool isValidBST(TreeNode *root) {
- f(root);
- return flag;
- }
相关热门文章
给主人留下些什么吧!~~
评论热议