leetcode 101: Symmetric Tree
来源:互联网 发布:微博发淘宝客链接 编辑:程序博客网 时间:2024/06/06 10:59
问题描述:
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]
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
[1,2,2,#,3,#,3]
1
/ \
2 2
\ \
3 3
思路:
碰到树,而且还是看起来挺复杂的问题,一条路走到黑想不通,那么基本上都需要用递归来解决。递归就要形成可迭代的问题,构造可迭代函数,原来的 isSymmetric 不符合迭代两个镜面的比较这种递归,所以很容易想到要另写一个函数,该函数需要能够递归地调用自己。
由于每步比较是否对称时,都需要比较每一层对应的两个节点是否如此,所以可以写一个函数是使用两个节点输入作比较的。
想清楚这些,剩下的就是注意各项出口的严密性了。
代码:
class Solution {public: bool isSymmetric(TreeNode* root) { if (root == NULL) return true; return isMirror(root->left,root->right); } bool isMirror(TreeNode *left, TreeNode *right) { if (left == NULL && right == NULL) return true; else if (left != NULL && right != NULL) { if (left->val != right->val) return false; // compare the mirror nodes pair else return (isMirror(left->left, right->right) && isMirror(left->right, right->left)); //form the mirror nodes pair } else return false; }};
0 0
- LeetCode(101)Symmetric Tree
- LeetCode 101 Symmetric Tree
- LeetCode: Symmetric Tree [101]
- [leetcode 101] Symmetric Tree
- [LeetCode 101]Symmetric Tree
- leetcode-101 Symmetric Tree
- leetcode || 101、Symmetric Tree
- Leetcode[101]-Symmetric Tree
- leetcode[101]:Symmetric Tree
- LeetCode 101 Symmetric Tree
- leetcode 101 Symmetric Tree
- Leetcode# 101 Symmetric Tree
- leetcode 101: Symmetric Tree
- leetCode #101 Symmetric Tree
- leetcode-101-Symmetric Tree
- leetcode 101 Symmetric Tree
- LeetCode 101: Symmetric Tree
- 【LEETCODE】101-Symmetric Tree
- 22,23?
- oracle 数据库收费标准
- 喷水装置(二)(南阳oj12)(贪心之区间覆盖问题)
- centos6.4安装搭建pptp vpn服务
- 使用cout输出两位小数
- leetcode 101: Symmetric Tree
- Linux BUS error问题记录
- SDK23版本之后的android-support-v7-gridlayout在AndroidStudio中的使用
- __weak如何实现对象值自动设置为nil的
- Unity中3中坐标系
- 利用 Spring MVC 和 RestTemplate 实现 CorsProxy
- 让php Session 存入 redis 配置方法
- 基于javaConfig的springDataJpa+dubbo+springMvc搭建(二)
- 在构造和析构中抛出异常