Symmetric Tree -- leetcode
来源:互联网 发布:阿里云登陆 编辑:程序博客网 时间:2024/06/16 11:10
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/** * 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) { list<TreeNode *> queue; queue.push_back(root); int count = 1; while (!queue.empty()) { TreeNode *node = queue.front(); queue.pop_front(); if (node) { queue.push_back(node->left); queue.push_back(node->right); } count--; if (!count) { list<TreeNode *>::iterator left = queue.begin(); list<TreeNode *>::reverse_iterator right = queue.rbegin(); for (int i=0; i<queue.size()/2; i++, left++, right++) { if (!*left && !*right) continue; if (!*left || !*right) return false; if ((*left)->val != (*right)->val) return false; } count = queue.size(); } } return true; }};
本算法基于广度优遍历。
将每一层放置在队列中后,进行类似回文的对比。
有些算法是将val值存入队列,不足之处,是需要定义一个特殊的整型值表示NULL结点。
本算法直接将结点指针存入队列,克服这个缺点。
且不需要在入口处判断root是否为空。
0 0
- Leetcode - Tree - Symmetric Tree
- Leetcode - Tree - Symmetric Tree
- LeetCode[Tree]: Symmetric Tree
- [leetcode][tree] Symmetric Tree
- LeetCode: Symmetric Tree
- [Leetcode] Symmetric Tree
- LeetCode : Symmetric Tree
- leetcode 13:symmetric tree
- [LeetCode] Symmetric Tree - Recursively
- [LeetCode] Symmetric Tree - Iteratively
- [LeetCode] Symmetric Tree
- [LeetCode]Symmetric Tree
- Leetcode:Symmetric Tree
- [Leetcode]Symmetric Tree
- Leetcode: Symmetric Tree
- [leetcode]Symmetric Tree
- LeetCode-Symmetric Tree
- [leetcode] Symmetric Tree
- Linux上安装LAMP
- 【转】uint8_t是什么数据类型
- Android 四大组件之一 Service
- Order Management Suite - Pricing and Availability Form Library
- Python如何打开外部文件?
- Symmetric Tree -- leetcode
- 汇编参数入栈的理解
- win7 64位与Ubuntu14.10 64位启动的问题
- gem5 se.py总结
- 黑马程序员--java高新技术--反射
- Kmeans K值的确定
- jQuery获取url链接
- RAM,SRAM,SDRAM,DDR SDRAM区别
- hibernate4实战1—入门