LeetCode题解——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.

递归判断左子树是否是平衡二叉树,递归判断右子树是否是平衡二叉树.easy to write code.

第一种:构造深度获得的递归函数,返回类型为int,从int值判断是否为平衡二叉树。

/**
 * 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) return true;
        int l = depthOfBinaryTree(root->left);
        int r = depthOfBinaryTree(root->right);
        if(l<0 || r<0) return false;
        if(abs(l-r)>1) return false;
        return true;
    }
    int depthOfBinaryTree(TreeNode *root){
        if(!root) return 0;
        int l = depthOfBinaryTree(root->left);
        int r = depthOfBinaryTree(root->right);
        if(l<0 || r<0) return -1;
        if(abs(l-r)>1) return -1;
        return (l>r?l:r)+1;
    }
};

第二种:构造递归函数,返回值为bool,传参与指针参数,通过指针参数返回深度值,通过函数返回值,判断是否为平衡二叉树。

/**
 * 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) {
        int d = 0;
        return isBalanced(root,&d);
    }
    bool isBalanced(TreeNode* root, int* d){
        if(!root){*d=0;return true;}
        int d1,d2;
        bool flage1 = isBalanced(root->left,&d1) && isBalanced(root->right,&d2);
        bool flage2 = ((abs(d1-d2))<2);
        *d = (d1>d2?d1:d2)+1;
        return flage1 && flage2;
    }
};


你可能感兴趣的:(LeetCode,tree,binary,depth)