Symmetric Tree
来源:互联网 发布:程序打包软件 编辑:程序博客网 时间:2024/06/04 00:54
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.
判断树是不是对称的,这边分别利用一个队列来记录下一层节点的情况,然后进行判断。特别注意空树和只有根节点的树这两种特殊情况!!!
还有就是对给的第二个例子的那种情况,左右进入队列都要进行判断!当然,也可以用栈来实现。
/** * 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){if (!root)return true;queue<TreeNode*>qleft;queue<TreeNode*>qright;if(root->left) qleft.push(root->left);if(root->right) qright.push(root->right);if(qleft.size()!=qright.size()) return false;while (!qleft.empty() && !qright.empty()){if (qleft.front()->val != qright.front()->val)return false;if (qleft.front()->left)qleft.push(qleft.front()->left);if (qright.front()->right)qright.push(qright.front()->right);if (qleft.size() != qright.size())return false;if (qleft.front()->right)qleft.push(qleft.front()->right);if (qright.front()->left)qright.push(qright.front()->left);qleft.pop();qright.pop();if (qleft.size() != qright.size())return false;}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
- 使用ioctl()函数获取ARP高速缓存例子的c实现
- 练习
- C++11 标准新特性: 右值引用与转移语义
- 【cocos2d-x 每天一学】(3)导入eclipse
- 0010 数据库对象—存储过程
- Symmetric Tree
- hdu 1166
- C# 进制转换
- 0011 数据库 游标
- 中断处理的上半部分和下半部分
- frame-relay intf-type
- 0012数据库 事务
- 数据库操作的常见错误
- typedef和define的区别