判断一棵树是否为搜索二叉树和完全二叉树

#include "Tree.h"
using namespace std;
//判断是否为搜索二叉树
bool isBST(Node* head)
{
    if(head == nullptr)
        return true;
    bool res = true;
    Node* pre = nullptr;
    Node* cur1 = head;
    Node* cur2 = nullptr;
    while(cur1)
    {
        cur2 = cur1->left;
        if(cur2)
        {
            while(cur2->right && cur2->right != cur1)
                cur2 = cur2->right;
            if(cur2->right == nullptr)
            {
                cur2->right = cur1;
                cur1 = cur1->left;
                continue;
            } else {
                cur2->right = nullptr;
            }
        }
        if(pre != nullptr && pre->value > cur1->value)
            res = false;
        pre = cur1;
        cur1 = cur1->right;
    }
    return res;
}
//判断是否是完全二叉树
bool isCBT(Node* head)
{
    if(head == nullptr)
        return true;
    queue<Node*> nQue;
    bool leaf = false;
    Node* L = nullptr;
    Node* R = nullptr;
    nQue.push(head);
    while(!nQue.empty())
    {
        head = nQue.front();
        nQue.pop();
        L = head->left;
        R = head->right;
        if((R && !L) || (leaf && (L || R)))
            return false;
        if(L)
        nQue.push(L);
        if(R)
            nQue.push(R);
        else
            leaf = true;
    }
    return true;
}
int main()
{
    Node* pNode0 = new Node(5);
    Node* pNode1 = new Node(3);
    Node* pNode2 = new Node(7);
    Node* pNode3 = new Node(2);
    Node* pNode4 = new Node(5);
    Node* pNode5 = new Node(6);
    Node* pNode6 = new Node(8);

    connectTree(pNode0, pNode1, pNode2);
    connectTree(pNode1, pNode3, pNode4);
    connectTree(pNode2, pNode5, pNode6);

    cout << isBST(pNode0) << endl;
    cout << isCBT(pNode0) << endl;
}

猜你喜欢

转载自blog.csdn.net/wzc2608/article/details/80870064