Leetcode 101 Symmetric Tree 判断一棵树是否对称
2018-03-24 20:20
579 查看
题目描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree
/ \
2 2
/ \ / \
3 4 4 3
But the following
1
/ \
2 2
\ \
3 3
思路:
1.(做法来自讨论区)判断一棵树是否是左右对称的,只需要判断它的左右孩子是互为镜面的,而这样的两棵树的镜面判断可以极为轻松地化为两棵树的判等问题(只不过左=左需要变成左=右)参见Leetcode 100,看来leetcode把这两道题放在一起是良苦用心啊
2.时间复杂度O(n)
代码:/**
* 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)
{return isMirror(root, root);}
bool isMirror(TreeNode* p, TreeNode *q)
{
if(!p && !q) return true;
if((!p && q) || (p && !q)) return p==q;
return ((p->val == q->val) && isMirror(p->right, q->left) && isMirror(p->left, q->right));
}
};
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).For example, this binary tree
[1,2,2,3,4,4,3]is symmetric: 1
/ \
2 2
/ \ / \
3 4 4 3
But the following
[1,2,2,null,3,null,3]is not:
1
/ \
2 2
\ \
3 3
思路:
1.(做法来自讨论区)判断一棵树是否是左右对称的,只需要判断它的左右孩子是互为镜面的,而这样的两棵树的镜面判断可以极为轻松地化为两棵树的判等问题(只不过左=左需要变成左=右)参见Leetcode 100,看来leetcode把这两道题放在一起是良苦用心啊
2.时间复杂度O(n)
代码:/**
* 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)
{return isMirror(root, root);}
bool isMirror(TreeNode* p, TreeNode *q)
{
if(!p && !q) return true;
if((!p && q) || (p && !q)) return p==q;
return ((p->val == q->val) && isMirror(p->right, q->left) && isMirror(p->left, q->right));
}
};
相关文章推荐
- LeetCode-101-Symmetric Tree(判断是否为对称树)
- Leetcode 101. Symmetric Tree 判断二叉树是否对称,注意写在两个方法中,递归时注意空的判断
- 二叉树系列 - [LeetCode] Symmetric Tree 判断二叉树是否对称,递归和非递归实现
- Symmetric Tree 判断一棵树是否对称
- 【LeetCode】Symmetric Tree 判断一棵树是否是镜像的
- 二叉树系列 - [LeetCode] Symmetric Tree 判断二叉树是否对称,递归和非递归实现
- [LeetCode] Symmetric Tree 判断二叉树是否为对称二叉树
- LeetCode(Symmetric Tree)判断二叉树是否是对称的
- Leetcode-Symmetric Tree——判断二叉树是否对称
- 【LeetCode101-110】二叉树对称及存储,前序中序遍历生成二叉树,中序后序生成二叉树,数组转化为AVL平衡树,判断二叉树是否平衡
- [LeetCode] Symmetric Tree 判断二叉树是否为对称二叉树
- 101. Symmetric Tree (判断二叉树是否对称)
- leetcode_Symmetric Tree_判断二叉树镜像对称_easy_方法
- 【LeetCode笔记】判断一棵树是否为镜像
- 【leetcode 二叉树对称判断】Symmetric Tree
- 【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】
- leetcode_101. Symmetric Tree 对称树, 判断一棵二叉树是否对称,递归方法
- LeetCode 101. Symmetric Tree(对称的树)
- leetcode 110-判断一棵树是否为平衡二叉树
- 【LeetCode-面试算法经典-Java实现】【101-Symmetric Tree(对称树)】