110. Balanced Binary Tree

题目

判断一棵二叉树是否为平衡二叉树(所有左右子树深度相差不超过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:
    bool isBalanced(TreeNode* root) {
        if(root==nullptr) return true;

        queue<TreeNode*> tree;
        tree.push(root);

        while(!tree.empty()){
            TreeNode* temp = tree.front();
            tree.pop();
            if(abs(countHeight(temp->left)-countHeight(temp->right))>1) return false;
            if(temp->left) tree.push(temp->left);
            if(temp->right) tree.push(temp->right);
        }

        return true;
    }

    int countHeight(TreeNode* root){
        if(root==nullptr) return 0;
        int leftHeight = 0;
        int rightHeight = 0;

        leftHeight = countHeight(root->left);
        rightHeight = countHeight(root->right);
        return max(leftHeight, rightHeight)+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:
    bool isBalanced(TreeNode* root) {
       if(countHeight(root)==-1) return false;
       else return true;
    }

    int countHeight(TreeNode* root){
       if(root==nullptr) return 0;

       int lHeight = countHeight(root->left);
       if(lHeight==-1) return -1;

       int rHeight = countHeight(root->right);
       if(rHeight==-1) return -1;

       if(abs(lHeight-rHeight)>1) return -1;

       return max(lHeight,rHeight)+1;
    }
};

你可能感兴趣的:(LeetCode,二叉树)