判断平衡的二叉树

【问题描述】

给出一个二叉树,判断其是否是一个高度平衡的二叉树。其中 数值为-1 代表该节点为NIL

【输入形式】

第一行:输入节点的数量

第二行:各个节点的数值
【输出形式】

若为高度平衡的二叉树,输出1,否则输出0
【样例输入】

7

3 9 20 -1 -1 15 7
【样例输出】

1

【样例输入】

9

1 2 2 3 3 -1 -1 4 4
【样例输出】

0

【样例说明】

在上述样例输入中 1 2 2 3 3 -1 -1 4 4所示树的形状为

              1

           /     \

       2             2

     /  \          /   \

   3     3      NIL   NIL

 /  \

4   4

思路

分为两部分:建立树,判断。
层次遍历建树用栈实现,判断用递归。

#include <iostream>
#include <queue>
#include<vector>
using namespace std;

class BinaryTree{
private:
    struct Node{//二叉树的结点类
        Node*left,*right;
        int data;
        Node():left(NULL),right(NULL){}
        Node(int item,Node *L=NULL,Node *R=NULL):data(item),left(L),right(R){}
    };
    Node *root;//二叉树的根节点
    int height(Node*t,int &flag){
        if (t==NULL) return 0;
        if (abs(height(t->left,flag)-height(t->right, flag))>1) {
            flag=0;
        }
        return max(height(t->left,flag),height(t->right,flag))+1;
    }
    
public:
    void createTree(){
        Node*tmp;int k=1;
        queue<Node *>que;
        int x=0,ldata=0,rdata=0,n=0;
        cin>>n;
        cin>>x;
        root=new Node(x);
        que.push(root);
        while(k<n){
            tmp=que.front();
            que.pop();
            cin>>ldata>>rdata;k+=2;
            if (ldata!=-1) {
                que.push(tmp->left=new Node(ldata));
            }
            if (rdata!=-1) {
                que.push(tmp->right=new Node(rdata));
            }
        }
    }
    int judge(){
        int flag=1;
        height(root, flag);
        return flag;
    }

};
int main() {
    BinaryTree T;
    T.createTree();
    cout<<T.judge();
    return 0;
}

若将-1改成任意符号

    void createTree(Type flag){
        Node*tmp;
        queue<Node *>que;
        Type x,ldata,rdata;
        cout<<"\n输入根节点:";
        cin>>x;
        root=new Node(x);
        que.push(root);
        while(!que.empty()){
            tmp=que.front();
            que.pop();
            cout<<"\n输入"<<tmp->data<<"的两个儿子"<<flag<<"表示空结点";
            cin>>ldata>>rdata;
            if (ldata!=flag) {
                que.push(tmp->left=new Node(ldata));
            }
            if (rdata!=flag) {
                que.push(tmp->right=new Node(rdata));
            }
        }
        cout<<"create completed!\n";
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值