是否是二叉搜索树 check if it is binary search tree

来源:互联网 发布:程序员大牛博客 编辑:程序博客网 时间:2024/06/03 12:08

是否是二叉搜索树 check if it is binary search tree

相关问题:找出最大的BST

geekforgeeks 给出了一个自顶向下的递归算法。自顶向下的思路:从根节点开始,向左右子树进发,逐步缩小范围。
我给出一个自下朝上的递归算法。
思路是:先判断左子树和右子树是不是BST。如果有一个不是,那么整个树就不是。如果两个子树都是,那么再看根节点值的大小。

#include<iostream>#include<stdio.h>#include<stdlib.h>using namespace std;#include <string.h>#include <stack>#include <stdio.h>#include <stdlib.h>struct Node{    int data;   Node* left;  Node* right;    Node(int k, Node* l, Node* r): data(k), left(l), right(r){};};void isBSTorNot(Node* root, bool& isBST, int& lowerBound, int& upperBound){if( root ){isBST = true;lowerBound = 0; // meaningless number here, they will be ignored in the recursion call stackupperBound = 0; // meaningless number here, they will be ignored in the recursion call stackreturn;}bool isBST1, isBST2;int lBd1, uBd1, lBd2, uBd2;isBSTorNot(root->left, isBST1, lBd1, uBd1);isBSTorNot(root->right, isBST2, lBd2, uBd2);if(root->left==NULL && root->right ==NULL){// 如果root是个叶子节点lowerBound = root->data;upperBound = root->data;isBST = true;return;}if(root->left==NULL){//如果root是没有左子树if(isBST2 && root->data < lBd2){isBST = true;lowerBound = root->data;upperBound = uBd2;}elseisBST = false;}if(root->right==NULL){//如果root是没有右子树if(isBST1 && root->data > uBd1){isBST = true;lowerBound = lBd1;upperBound = root->data;}elseisBST = false;}if(isBST1 && isBST2 && root->data < lBd2 && root->data > uBd1){isBST = true;lowerBound = lBd1;upperBound = uBd2;}elseisBST = false;}void printTree(Node* root)  {      if(root==NULL)          return;        cout<<root->data<<" ";      printTree(root->left);         printTree(root->right);    }  int main(){    Node* n1 = new Node(1,NULL,NULL);        Node* n3 = new Node(3,NULL,NULL);        Node* n2 = new Node(2,n1,n3);        Node* n5 = new Node(5,NULL,NULL);        Node* n4 = new Node(4,n2,n5);       Node* n0 = new Node(0,NULL,n4);  /* Constructed binary tree is          0         \          4          /   \       2     5        /  \    1     3  */ int l, r;bool b = false;isBSTorNot(n4, b, l, r);if(b)cout<<"fffff"<<endl;}


0 0
原创粉丝点击