Symmetric Tree
来源:互联网 发布:淘宝店信誉级别 编辑:程序博客网 时间:2024/06/01 07:42
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 a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSymmetric(TreeNode* root) { if(root == NULL){ return true; }else if(root->left == NULL && root->right == NULL){ return true; }else{ queue<TreeNode*> lTree; queue<TreeNode*> rTree; if(isSame(root->left,root->right)){ lTree.push(root->left); rTree.push(root->right); }else{ return false; } while(!lTree.empty() && !rTree.empty()){ TreeNode* lfront = lTree.front(); TreeNode* rfront = rTree.front(); lTree.pop(); rTree.pop(); if(!isSame(lfront->right,rfront->left)){ return false; } if(lfront->right!=NULL && rfront->left!=NULL){ lTree.push(lfront->right); rTree.push(rfront->left); } if(!isSame(lfront->left,rfront->right)){ return false; } if(lfront->left!=NULL && rfront->right!=NULL){ lTree.push(lfront->left); rTree.push(rfront->right); } } return true; } } bool isSame(TreeNode* a,TreeNode* b){ if(a == NULL && b == NULL){ return true; }else if(a != NULL && b == NULL){ return false; }else if(a == NULL && b != NULL){ return false; }else{ if(a->val == b->val){ return true; }else{ return false; } } } };
解法二:递归形式
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSymmetric(TreeNode* root) { if(root == NULL){ return true; }else{ return isSame(root->left,root->right); } } bool isSame(TreeNode* a,TreeNode* b){ if(a == NULL && b == NULL){ return true; }else if(a != NULL && b == NULL){ return false; }else if(a == NULL && b != NULL){ return false; }else{ if(a->val == b->val){ return isSame(a->right,b->left) && isSame(a->left,b->right); }else{ return false; } } }};
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
- - addChildViewController控制器切换
- java微信网页授权获取用户信息以及JSSDK自定义分享等功能<二>
- iPhone App自动化测试工具总结
- 串口工具选择
- Android Data Binding代码实战
- Symmetric Tree
- 偶然
- 前端框架 - 学习方法
- 【Codeforces Round 271 (Div 2)C】【暴力 坐标变换】Captain Marmot 四个点绕中心旋转 最小步数使得构成正方形
- Data Structure(1-5)---单链表的插入与删除
- Tomcat服务无法启动的问题的解决方法
- Java Base —— 注解
- eclipse转Android studio
- opencv学习(9)利用形态滤波学检测角点