c++判断搜索二叉树、完全二叉树

搜索二叉树:中序遍历为升序
任意一个节点的值一定大于该节点左子树中的任意一个节点的值,同时满足该节点的值小于其右子树中的任意一个节点的值(解决效率问题)
方法:非递归版本二叉树中序遍历,把打印过程改成判断。

#include
#include
#include

using namespace std;

struct node{
     
    int value;
    node* left;
    node* right;
    node(int value):
        value(value), left(NULL),right(NULL) {
     }
};

bool isBST(node* head){
     
    if (head == NULL){
     
        return true;
    }
    stack<node*>newstack;
    int pre = INT_MIN;
    while (!newstack.empty() || head != NULL){
     
        if (head != NULL){
     
            newstack.push(head);
            head = head->left;
        }
        else{
     
            head = newstack.top();
            //cout << head->value << ",";
            if (pre < head->value){
     
                pre = head->value;
            }else{
     
                return false;
            }
            newstack.pop();
            head = head->right;
        }
    }
    return true;
}

int main(){
     
    node* head = new node(4);
    head->left = new node(2);
    head -> right = new node(6);
    head->left->left = new node(1);
    head->left->right = new node(3);
    head->right->left = new node(5);
    head->right->right = new node(7);
    cout << isBST(head) << endl;
}


完全二叉树:
思路:
1)如果有右孩子,没有左孩子,那肯定不是完全二叉树
2)当第一次发现左右两个孩子不是双全的时候,后面遍历到的节点全部都是叶节点,否则返回false

#include
#include
using namespace std;

struct node{
     
    int value;
    node* left;
    node* right;
    node(int value):
        value(value), left(NULL),right(NULL) {
     }
};

bool isCST(node* head){
     
    if(head == NULL){
     
        return true;
    }
    queue <node*> q;
    bool leaf = false;
    node* l = NULL;
    node* r = NULL;
    q.push(head);
    while (!q.empty()){
     
        head = q.front();
        l = head->left;
        r = head->right;
        if ((leaf && (l != NULL || r != NULL))
            ||
            (l == NULL && r != NULL)){
     
            return false;
            }
        if (l != NULL){
     
            q.push(l);
        }
        if (r != NULL){
     
            q.push(r);
        }
        else{
     
            leaf = true;
        }
        q.pop();
    }

    return true;
}

int main(){
     
    node* head = new node(1);
    head->left = new node(2);
    head->right = new node(3);
    head->left->left = new node(4);
    head->left->right = new node(5);
    head->right->left = new node(6);
    cout << isCST(head) << endl;
}


你可能感兴趣的:(算法与结构,二叉树,算法)