110:Balanced Binary Tree【树】【DFS】

题目链接:click~

/*题意:判断一颗平衡二叉树是否平衡*/

/**
 *思路:平衡二叉树的每个结点的左右子树的深度差不超过1
 *      DFS记录每个结点的左右子树的深度,判断是否平衡
 */

class Solution {

public:
    bool Judge(TreeNode *T, int &dep) {
        if(T == NULL) {
            dep = 0;
            return true;
        }

        int leftdepth, rightdepth;
        bool leftBalance = Judge(T->left, leftdepth);
        bool rightBalance = Judge(T->right, rightdepth);

        dep = max(leftdepth, rightdepth) + 1;

        return leftBalance && rightBalance && (abs(leftdepth-rightdepth) <= 1);
    }
    bool isBalanced(TreeNode *root) {
        int dep;
        return Judge(root, dep);
    }
};


你可能感兴趣的:(leetcode)