#include<iostream>
#include<queue>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(){}
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
void pretravel(TreeNode* root){
if (root == NULL){
return;
}
else{
cout << root->val << " ";
pretravel(root->left);
pretravel(root->right);
}
}
//建立二叉树通过一数组
TreeNode* buildCore(int *piValue, int Start, int Length){
if (Start>= Length){
return NULL;
}
TreeNode *pRoot = new TreeNode;
if (piValue[Start] == 0) pRoot = NULL;
else{
pRoot->val = piValue[Start];
pRoot->left = buildCore(piValue, Start*2+1, Length);
pRoot->right = buildCore(piValue, Start*2+2, Length);
}
return pRoot;
}
int isEvenOddTree(TreeNode *root){
queue<TreeNode*>Q;
Q.push(root);
int level = 0;
while(!Q.empty()){
int pre = level % 2 == 0 ? INT_MIN :INT_MAX;
int len = Q.size() ;
for(int i = 0;i < len;i++){
TreeNode* node = Q.front();
Q.pop();
int value = node->val;
if(value % 2 == level % 2) return false;
if((level % 2 == 0 && pre >= value) ||(level % 2 == 1 && pre <= value)) return false;
pre = value;
if(node->left){
Q.push(node->left);
}
if(node->right){
Q.push(node->right);
}
}
level++;
}
return true;
}
int main(){
TreeNode* Tree;
int root1[15] = {1,10,4,3,0,7,9,12,8,0,0,6,0,0,2};
int* a = root1;
Tree = buildCore(a,0,15);
cout << isEvenOddTree(Tree) << endl;
return 0;
}
leetcode 奇偶数
最新推荐文章于 2024-11-01 15:19:21 发布