LeetCode-Balanced Binary Tree

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isBalanced(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int dep;
        return checkBalance(root, dep);
    }
    
    bool checkBalance(TreeNode *root, int &dep)
    {
        if (root == NULL)
        {
            dep = 0;
            return true;
        }
        int leftDep;
        int rightDep;
        bool leftBalance = checkBalance(root->left, leftDep);
        bool rightBalance = checkBalance(root->right, rightDep);
        dep = 1 + max(leftDep, rightDep);
        int diff = abs(leftDep - rightDep);
        return diff <= 1 && leftBalance && rightBalance;
    }
};

發佈了124 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章