二叉树的深度并判断是否是平衡二叉树

#include <iostream>
using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left,*right;
};

void preOrderTraverse(TreeNode *p)
{
    if(p)
    {
        cout<<p->val<<" ";
        preOrderTraverse(p->left);
        preOrderTraverse(p->right);
    }
}

void create(TreeNode *&p)
{
    int k;
    cin>>k;
    if(k!=0)
    {
        p=new TreeNode;
        p->val=k;
        create(p->left);
        create(p->right);
    }
    else
        p=NULL;
}

int TreeDepth(TreeNode *root) //二叉树的深度
{
    if(root==NULL)
        return 0;
    int left=TreeDepth(root->left);
    int right=TreeDepth(root->right);
    return left>right?left+1:right+1;
}

bool isbalanced2(TreeNode *root,int &depth)
{
    if(root==NULL)
    {
        depth=0;
        return true;
    }
    int left,right;
    if(isbalanced2(root->left,left)&&isbalanced2(root->right,right))
    {
        int diff=left-right;
        if(diff<=1&&diff>=-1)
        {
            depth=left>right?left+1:right+1;
            return true;
        }
    }
    return false;
}

/*是否为一棵平衡二叉树,遍历树的每个节点,调用TreeDepth得到
左右子树的深度,相差不超过1,就是平衡二叉树。*/
bool isbalanced1(TreeNode *root)  
{
    if(root==NULL)
        return true;
    int left=TreeDepth(root->left);
    int right=TreeDepth(root->right);
    int diff=left-right;
    if(diff>1||diff<-1)
        return false;
    return isbalanced1(root->left)&&isbalanced1(root->right);
}

int main()
{
    TreeNode *root=NULL;
    create(root);

    preOrderTraverse(root);
    cout<<endl<<TreeDepth(root)<<endl;
    cout<<isbalanced1(root)<<endl;
    int depth=0;
    cout<<isbalanced2(root,depth);
}

 

posted @ 2017-05-01 22:33  home普通的人  阅读(267)  评论(0编辑  收藏  举报