LeetCode 문제: Balanced Binary Tree

1617 단어 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.
생각:
두 갈래 나무의 균형 조건은 왼쪽 나무의 균형과 오른쪽 나무의 균형, 왼쪽 나무의 높이 차이가 최대 1이다.이 사고방식에 근거하여 점차 처리하다.
문제:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    pair<bool, int> TraverseProc(const TreeNode* node)
    {
        if (node == nullptr)
            return make_pair(true, 0);
            
        // check left branch
        pair<bool, int> left_balance=TraverseProc(node->left);
        if (!left_balance.first) return make_pair(false, 0);
        
        // check right branch
        pair<bool, int> right_balance=TraverseProc(node->right);
        if (!right_balance.first) return make_pair(false, 0);
        
        // check the current node
        int balance_factor = left_balance.second - right_balance.second;
        if (balance_factor>1 || balance_factor<-1)
            return make_pair(false, 0);
        else
            return make_pair(true, max(left_balance.second, right_balance.second)+1);
    }

    bool isBalanced(TreeNode *root) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        return TraverseProc(root).first;
    }
};

좋은 웹페이지 즐겨찾기