首页 > 代码库 > LeetCode "Balanced Binary Tree"

LeetCode "Balanced Binary Tree"

Another recursion problem.

class Solution {public:    int getHeight(TreeNode *p)    {        if (!p) return 0;        int hL = 1;        if (p->left) hL = 1 + getHeight(p->left);        int hR = 1;        if (p->right) hR = 1 + getHeight(p->right);        return (hL > hR ? hL : hR);    }    bool isBalanced(TreeNode *root) {        if (!root || (!root->left && !root->right)) return true;        bool bLeft = isBalanced(root->left);        if (!bLeft) return false;        bool bRight = isBalanced(root->right);        if (!bRight) return false;        {            int hL = getHeight(root->left);            int hR = getHeight(root->right);            if (abs(hL - hR) < 2) return true;        }        return false;    }};