平衡二叉树判断练习

来源:互联网 发布:mac怎么输入罗马数字 编辑:程序博客网 时间:2024/05/17 03:54

有一棵二叉树,请设计一个算法判断这棵二叉树是否为平衡二叉树。
给定二叉树的根结点root,请返回一个bool值,代表这棵树是否为平衡二叉树。

采用后续遍历的递归算法.

/*struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :            val(x), left(NULL), right(NULL) {    }};*/class CheckBalance {public:    bool check(TreeNode* root) {        int heigh=0;        return recurcheck(root,heigh);    }    bool  recurcheck(TreeNode* root,int &heigh)        {        int lh,rh;        if(!root)            {            heigh=0;            return true;        }        if(recurcheck(root->left,lh)&&recurcheck(root->right,rh))            {            if(abs(lh-rh)>1)                return false;            heigh=max(lh,rh)+1;            return true;                   }        else            return false;    }};
0 0
原创粉丝点击