38、平衡二叉树

题目描述:

  输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里插入图片描述

解题思路:

  在遍历树的每个结点的时候,调用函数TreeDepth得到它的左右子树的深度。如果每个结点的左右子树的深度相差都不超过1,按照定义它就是一棵平衡的二叉树。一边遍历一边判断是否是平衡二叉树

Demo:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        return TreeDepth(pRoot) != -1;
    }
    int TreeDepth(TreeNode* pRoot){
        if (pRoot == nullptr) return 0;
        int nleft = TreeDepth(pRoot->left);
        // 如果当前结点左子树的高度为-1,则说明当前结点不满足要求
        if (nleft == -1) return -1; 
        int nright = TreeDepth(pRoot->right);
        // 如果当前结点右子树的高度为-1,则说明当前结点不满足要求
        if (nright == -1) return -1;
        // 先判断当前结点是否满足平衡二叉树的要求,不满足直接返回高度为-1
        return (abs(nleft - nright) > 1) ? -1 : max(nleft, nright) + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/daaikuaichuan/article/details/89761326