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.

http://oj.leetcode.com/problems/balanced-binary-tree/


Solution:

Modified from get binary tree depth. Recursively compare the depth difference of every left subtree and right subtree.

https://github.com/starcroce/leetcode/blob/master/balanced_binary_tree.cpp

// 64 ms for 226 test cases
/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(root == NULL) {
            return true;
        }
        int diff = getDepth(root->left) - getDepth(root->right);
        if(abs(diff) > 1) {
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }
    
    int getDepth(TreeNode *root) {
        if(root == NULL) {
            return 0;
        }
        int leftDepth = getDepth(root->left);
        int rightDepth = getDepth(root->right);
        return max(leftDepth, rightDepth) + 1;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章