반응형

https://leetcode.com/problems/even-odd-tree

 

Even Odd Tree - LeetCode

Can you solve this real interview question? Even Odd Tree - A binary tree is named Even-Odd if it meets the following conditions: * The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc

leetcode.com

 

BFS로 풀 수 있었습니다.

각 depth별로 좌측 노드부터 순차적으로 순회하며, 조건에 맞는지 확인해줍니다. 

class Solution {
public:
    bool isEvenOddTree(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);

        bool asc = true;
        while(!q.empty()) {
            int sz = q.size();
            int cur = asc ? INT_MIN : INT_MAX;
            while(sz--) {
                TreeNode* node = q.front();
                q.pop();

                if(asc) {
                    if(!(node->val % 2) || node->val <= cur) return false;
                } else {
                    if(node->val % 2 || node->val >= cur) return false;
                }

                cur = node->val;

                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            asc = !asc;
        }

        return true;
    }
};
반응형

'Algorithm' 카테고리의 다른 글

LeetCode 19. Remove Nth Node From End of List  (0) 2024.03.03
LeetCode 977. Squares of a Sorted Array  (0) 2024.03.02
LeetCode 543. Diameter of Binary Tree  (1) 2024.02.29
LeetCode 268. Missing Number  (0) 2024.02.20
LeetCode 231. Power of Two  (0) 2024.02.19

+ Recent posts