|
| 1 | +#include "tree.h" |
| 2 | + |
| 3 | +//version 1 recursive |
| 4 | +bool symmetric( struct TreeNode* left, struct TreeNode* right ) |
| 5 | +{ |
| 6 | + if(!left && !right) |
| 7 | + return true; |
| 8 | + else if(!left || !right) |
| 9 | + return false; |
| 10 | + if(left->val != right->val) |
| 11 | + return false; |
| 12 | + |
| 13 | + return symmetric(left->left, right->right) && symmetric(left->right, right->left); |
| 14 | +} |
| 15 | + |
| 16 | +bool isSymmetric( struct TreeNode * root ) |
| 17 | +{ |
| 18 | + if(!root) |
| 19 | + return true; |
| 20 | + return symmetric(root->left, root->right); |
| 21 | +} |
| 22 | + |
| 23 | +//version 2 norecursive |
| 24 | +struct TreeNode** fillNext( struct TreeNode** stack, int size , int* newSize) |
| 25 | +{ |
| 26 | + struct TreeNode** t = ( struct TreeNode** )malloc(sizeof( struct TreeNode* )*2*size); |
| 27 | + int index = 0; |
| 28 | + for(int i = 0; i < size; i++) |
| 29 | + { |
| 30 | + if(stack[i]) |
| 31 | + { |
| 32 | + t[index++] = stack[i]->left; |
| 33 | + t[index++] = stack[i]->right; |
| 34 | + } |
| 35 | + } |
| 36 | + *newSize = index; |
| 37 | + return t; |
| 38 | +} |
| 39 | + |
| 40 | +bool isSymmetric( struct TreeNode * root ) |
| 41 | +{ |
| 42 | + if(!root || (!(root->left) && !(root->right))) |
| 43 | + return true; |
| 44 | + if(!root->left || !root->right) |
| 45 | + return false; |
| 46 | + |
| 47 | + int count = 1; |
| 48 | + struct TreeNode **lStack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); |
| 49 | + struct TreeNode **rStack = (struct TreeNode**)malloc(sizeof(struct TreeNode*)); |
| 50 | + lStack[0] = root->left; |
| 51 | + rStack[0] = root->right; |
| 52 | + |
| 53 | + while(count) |
| 54 | + { |
| 55 | + int lIndex = 0, rIndex = 0; |
| 56 | + for(int i = 0; i < count; i++) |
| 57 | + { |
| 58 | + if(!lStack[i] || !rStack[count-i-1]) |
| 59 | + { |
| 60 | + if(!lStack[i] && !rStack[count-i-1]) |
| 61 | + continue; |
| 62 | + return false; |
| 63 | + } |
| 64 | + if(lStack[i]->val != rStack[count-i-1]->val) |
| 65 | + return false; |
| 66 | + } |
| 67 | + int lCount=0, rCount=0; |
| 68 | + lStack = fillNext(lStack, count, &lCount); |
| 69 | + rStack = fillNext(rStack, count, &rCount); |
| 70 | + if(lCount != rCount) return false; |
| 71 | + count = lCount; |
| 72 | + } |
| 73 | + return true; |
| 74 | +} |
0 commit comments