首页 > 其他 > 详细

平衡二叉树

时间:2019-04-09 23:34:53      阅读:186      评论:0      收藏:0      [点我收藏+]

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 
解题思路:
这里所说的平衡二叉树不要求是搜索树,平常意义上的二叉平衡树一般都是指平衡二叉搜索树。
那么只需要判断任何一个节点的左右子树高度差是否大于1即可。
 
class Solution {
public:
    bool isBalanTree = true;
    int travalTree(TreeNode* root, int depth){
        if(root == NULL){
            return depth;
        }
        if(root->left == NULL && root->right == NULL){
            return depth;
        }
        int lh = depth;
        if(root->left != NULL){
            lh = travalTree(root->left, depth+1);
        }
        int rh = depth;
        if(root->right != NULL){
             rh = travalTree(root->right, depth+1);
        }
       // cout<< "lh="<<lh<< " rh=" <<rh<<endl;
        if((lh == depth && rh - depth > 1) || (rh == depth && lh - depth > 1) || abs(lh-rh) >1){
            isBalanTree = false;
        }
        return max(lh, rh);
    }
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(pRoot == NULL) return true;

        travalTree(pRoot, 1);

        return isBalanTree;
    }
};

  

平衡二叉树

原文:https://www.cnblogs.com/chengsheng/p/10680564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!