[leetcode-101]Symmetric Tree(c++)
2015-08-11 11:01
211 查看
问题描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
/ \
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.
代码如下: 递归版/4ms
代码如下:迭代版/4ms
(维护一个队列或者栈)
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
[code]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.
代码如下: 递归版/4ms
[code]/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool checkSym(struct TreeNode* leftNode,struct TreeNode* rightNode){ if(!leftNode || !rightNode) return leftNode==rightNode; if(leftNode->val != rightNode->val) return false; return checkSym(leftNode->right,rightNode->left) && checkSym(leftNode->left,rightNode->right); } bool isSymmetric(struct TreeNode* root) { if(!root) return true; return checkSym(root->left,root->right); }
代码如下:迭代版/4ms
(维护一个队列或者栈)
[code]class Solution { public: bool isSymmetric(TreeNode* root) { queue<TreeNode*> queue; if(!root) return true; queue.push(root->left); queue.push(root->right); TreeNode *front,*second; while(!queue.empty()){ front = queue.front();queue.pop(); second = queue.front();queue.pop(); if(!front || !second){ if(front!=second) return false; continue; } if(front->val!=second->val) return false; queue.push(front->right); queue.push(second->left); queue.push(front->left); queue.push(second->right); } return true; } };
相关文章推荐
- 利用C语言来求最大连续子序列乘积的方法
- c++防止迭代器失效
- 当C++遇到IOS应用开发---LRUCache缓存
- C++单例模式
- 使用C语言提取子字符串及判断对称子字符串最大长度
- C++11 并发指南六( <atomic> 类型详解二 std::atomic )
- 再说 c++11 内存模型
- OC语言-01-面向过程与面向对象思想
- C语言程序设计进阶
- c++迭代器失效2
- C++基础知识实例解析(一)
- 详解散列表算法与其相关的C语言实现
- C++ 回调函数的用法
- 线程池C++
- C++概念整理
- C++11 STL之emplace() 和 emplace_back()
- C++ Constructor
- C/C++知识要点6——定义只能在堆/栈上生成对象的类
- 朝鲜战争:轰炸大小和岛
- C与C++中const区别