1609. 奇偶树

该篇博客详细介绍了如何解决1609题——奇偶树的问题。通过定义一个辅助函数来判断节点值的奇偶性,并使用栈来实现层次遍历。在遍历过程中,确保同一层节点的值按照奇偶交替排列且值递增,从而验证树是否为奇偶树。文章提供了C++代码实现,包括关键的队列操作和节点遍历逻辑。
摘要由CSDN通过智能技术生成

​ 

链接:1609. 奇偶树

题解:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    bool is_oushu(int val) {
        return val % 2 == 0 ? true : false;
    }
    void push_node_neighboard_to_queue(bool jishu, std::stack<TreeNode*>& que, TreeNode* node) {
        if (jishu) {
            if (node->left) {
                que.push(node->left);
            }
            if (node->right) {
                que.push(node->right);
            }
        } else {
            if (node->right) {
                que.push(node->right);
            }
            if (node->left) {
                que.push(node->left);
            }
        }
    }
public:
    bool isEvenOddTree(TreeNode* root) {
        if (!root) {
            return true;
        }
        std::stack<TreeNode*> que;
        que.push(root);
        bool jishu = true;
        while (!que.empty()) {
            std::stack<TreeNode*> next_sta;
            int size = que.size();
            int prev_val = -1;
            for (int i = 0; i < size; ++i) {
                auto top = que.top();
                que.pop();
                if (jishu) {
                    if (is_oushu(top->val)) {
                        return false;
                    } 
                } else {
                    if (!is_oushu(top->val)) {
                        return false;
                    }
                }
                if (top->val <= prev_val) {
                    return false;
                }
                push_node_neighboard_to_queue(jishu, next_sta, top);
                prev_val = top->val;
            }
            jishu = !jishu;
            que = next_sta;
        }
        return true;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值