[leetcode] 110. Balanced Binary Tree 解题报告

题目链接:https://leetcode.com/problems/balanced-binary-tree/

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


思路:求解一个树是否平衡可以转化为求二叉树的深度,一旦发现左右子树深度相差超过1,则说明不是平衡树。

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int getDepth(TreeNode* root, bool& flag)
    {
        //如果当前节点为空则返回深度0,如果flag为false,说明已经判断这不是平衡树,结束程序
        if(!root || !flag) return 0;
        int dp1 = getDepth(root->left, flag);
        int dp2 = getDepth(root->right, flag);
        if(abs(dp1 - dp2) > 1) //如果左右子树深度差大于1,说明不是平衡树
            flag = false;
        return max(dp1, dp2) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if(root == NULL)    return true;
        bool flag = true;
        getDepth(root, flag);
        return flag;
    }
};


你可能感兴趣的:(LeetCode,算法,二叉树,tree,binary,DFS)