Symmetric Tree
来源:互联网 发布:淘宝上卖汽车用品 编辑:程序博客网 时间:2024/06/11 04:22
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSymmetric(TreeNode *root) { vector<int> arr(0); queue<TreeNode*> q; vector<int>::iterator index_begin,index_end; TreeNode *leaf; int cnt=1,i; int leaves=0; TreeNode *p = root; if(p==NULL) return true; q.push(p); while(!q.empty()){ arr.clear(); for(i=0,leaves=0;i<cnt;i++){ p=q.front(); arr.push_back(p->val); q.pop(); if(p->val==-999) continue; if(p->left!=NULL) { q.push(p->left); leaves++; } else { leaf=(TreeNode*)malloc(sizeof(TreeNode)); leaf->val=-999; q.push(leaf); leaves++; } if(p->right!=NULL) { q.push(p->right); leaves++; } else { leaf=(TreeNode*)malloc(sizeof(TreeNode)); leaf->val=-999; q.push(leaf); leaves++; } } cnt=leaves; if(cnt%2!=0) return false; index_begin=arr.begin(); index_end=arr.end()-1; while(index_begin<index_end){ if(*index_begin!=*index_end) return false; index_begin++; index_end--; } } return true; }};
0 0
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- Symmetric Tree
- auto int b=0 不能与其他类型说明符组合
- gsl_rng_alloc() exception问题
- 链队列
- 浅谈db2与oracle存储过程的不同之处
- 颜色特征
- Symmetric Tree
- Eclipse启动时;的调优处理
- VS2013 编译VC6.0等比较老版本的MFC工程字符集错误问题的解决方法
- Android改变系统自带ProgressDialog的文字大小
- system调用gcc编译器-待补充
- 异步回收fork出的子进程(僵尸进程)
- SSD5 option 5
- UVA - 10305 - Ordering Tasks (拓扑排序!)
- 屏蔽控制台应用程序的窗口#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")