101. Symmetric Tree
2016-05-25 11:44
169 查看
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
BFS 迭代
/**
* 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) return true;
stack<TreeNode*> sk;
sk.push(root->left);
sk.push(root->right);
TreeNode* pA, *pB;
while(!sk.empty()) {
pA = sk.top();
sk.pop();
pB = sk.top();
sk.pop();
if(!pA && !pB) continue;
if(!pA || !pB) return false;
if(pA->val != pB->val) return false;
sk.push(pA->left);
sk.push(pB->right);
sk.push(pA->right);
sk.push(pB->left);
}
return true;
}
};
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.
/** * 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 TreeCmp(TreeNode* p,TreeNode* q) { bool b1,b2; if(!p&&!q) return true; else if((!p&&q)||(p&&!q)) return false; else { if(p->val!=q->val) return false; else return TreeCmp(p->left,q->right)&&TreeCmp(p->right,q->left); } } bool isSymmetric(TreeNode* root) { if(!root) return true; return TreeCmp(root->left,root->right); } };
BFS 迭代
/**
* 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) return true;
stack<TreeNode*> sk;
sk.push(root->left);
sk.push(root->right);
TreeNode* pA, *pB;
while(!sk.empty()) {
pA = sk.top();
sk.pop();
pB = sk.top();
sk.pop();
if(!pA && !pB) continue;
if(!pA || !pB) return false;
if(pA->val != pB->val) return false;
sk.push(pA->left);
sk.push(pB->right);
sk.push(pA->right);
sk.push(pB->left);
}
return true;
}
};
相关文章推荐
- Win2003利用dfs(分布式文件系统)在负载均衡下的文件同步配置方案
- win2003分布式文件系统(dfs)配置方法[图文详解]
- win2003分布式文件系统及其部署 图文教程
- Hadoop2.6+jdk8的安装部署(1)——使用jar包安装部署【详细】
- Hadoop FS Shell
- DFS使用方法总结
- FastDFS注意事项
- 无忧技术带您预览DFS(分布式文件系统)管理控制台
- C 语言实现迷宫 DFS算法
- 一幅图弄清DFT与DTFT,DFS的关系
- HDFS---Namenode
- HDFS ---- Services startup
- POJ1523 SPF dfs
- poj1731 Orders dfs
- Surrounded Regions
- Binary Tree Zigzag Level Order Traversal,Restore IP Addresses,Word Search,Simplify Path
- DFS基础(1)
- HDU1241 Oil Deposits
- DFS算法有趣小题目
- HDU 1016 Prime Ring Problem