[LeetCode]Symmetric Tree
2015-12-05 12:48
483 查看
题目描述:(链接)
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.
解题思路:
递归版:
迭代版:
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 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 == nullptr) { return true; } return isSymmetric(root->left, root->right); } bool isSymmetric(TreeNode *left, TreeNode *right) { if (!left && !right) return true; if (!left || !right) return false; return left->val == right->val && isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left); } };
迭代版:
/** * 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 == nullptr) return true; stack<TreeNode *> cache; cache.push(root->left); cache.push(root->right); while (!cache.empty()) { auto p = cache.top(); cache.pop(); auto q = cache.top(); cache.pop(); if (!p && !q) continue; if (!p || !q) return false; if (p->val != q->val) return false; cache.push(p->left); cache.push(q->right); cache.push(p->right); cache.push(q->left); } return true; } };
相关文章推荐
- 看我linux(ubuntu)下的64位编译器编译32位程序
- 三证合一
- Git 常用命令
- suspend造成死锁的例子和原因分析 http://blog.csdn.net/magictong/article/details/4161571
- 自定义SurfaceView之加载GIF
- MyEclipse中的main()和System.out.println()的快捷键输入设置
- win10系统右下角登录微信和QQ时不显示图标怎么办?
- online_judge_1022
- (译)如何自定义UIDocument的子类
- imageView实现图片适屏和裁剪图片的功能
- Git 常用命令速查表(三)
- 线程天敌TerminateThread与SuspendThread http://blog.csdn.net/magictong/article/details/6304439
- Windows基于Apache的svn服务器配置
- 优秀程序员的七大特征,你具备几条?
- DDuilib入门【一】
- 清华大学出版社计算机图书出版,请联系我
- opencv 图片转视频
- 关于Eclipse打包签名失效的问题
- 265. Paint House II
- 【javascript】javascript闭包经典代码