leetCode(15):Symmetric Tree
2015-06-21 11:49
357 查看
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.
首先递归方法:
循环方法:把左右子树依次压入到容器中,并一层一层地判断,如果不平衡则立即返回;直至没有新的结点压入到容器中。
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.
首先递归方法:
bool isChildSymmectric(TreeNode* node1,TreeNode* node2) { if(node1==NULL && node2==NULL) return true; if(node1==NULL || node2==NULL || node1->val!=node2->val) return false; return isChildSymmectric(node1->left,node2->right) && isChildSymmectric(node1->right,node2->left); } bool isSymmetric(TreeNode* root) { if(root==NULL) return true; return isChildSymmectric(root->left,root->right); }
循环方法:把左右子树依次压入到容器中,并一层一层地判断,如果不平衡则立即返回;直至没有新的结点压入到容器中。
/** * 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; vector<TreeNode*> nodes; nodes.push_back(root); int nodesBegin=0; int nodesEnd=nodes.size(); while(nodesBegin<nodesEnd) { int b=nodesBegin; int e=nodes.size()-1; while(b<e) { if(nodes[b]==NULL && nodes[e]==NULL) { b++; e--; continue; } if((nodes[b]==NULL && nodes[e]) || (nodes[b] && nodes[e]==NULL) || (nodes[b]->val!=nodes[e]->val)) return false; nodes.push_back(nodes[b]->left); nodes.push_back(nodes[b]->right); b++; e--; } while(b<nodesEnd) { if(NULL==nodes[b]) { b++; continue; } nodes.push_back(nodes[b]->left); nodes.push_back(nodes[b]->right); b++; } nodesBegin=nodesEnd; nodesEnd=nodes.size(); } return true; } };
相关文章推荐
- leetCode(15):Symmetric Tree 分类: leetCode 2015-06-21 11:49 78人阅读 评论(0) 收藏
- 1.TomCat以及JavaWeb的开发目录结构
- POJ 1611 The Suspects(并查集)
- leetCode(14):Invert Binary Tree and Same Tree
- leetCode(14):Invert Binary Tree and Same Tree 分类: leetCode 2015-06-21 11:48 170人阅读 评论(0) 收藏
- slick与mysql
- 增强型for循环的各个参数
- 【麦可网】Cocos2d-X跨平台游戏开发学习笔记---第十三课:Cocos2D-X内存管理4-6
- activity-alias使用
- paperclip用lambda来动态定义 crop/resize 的图片大小
- 日语学习之沪江N3基础 20150621 -3
- Windows Phone 获取本地IP地址
- 教你21天学会C++ (有图有真相)
- leetcode--Implement Stack using Queues
- 渣渣ACM日记——278-排队(NYOJ)
- ubuntu日常使用常用快捷键(待补充)
- 长轮询解决方案
- 黑马程序员——学习日记之--Java网络编程小结
- 数组结对开发
- redis翻译_redis lua脚本