链接: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;
}
};