LeetCode-101. Symmetric Tree
2017-02-28 17:12
363 查看
问题:https://leetcode.com/problems/symmetric-tree/?tab=Description
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
分析:对称树的左右子树也是相互对称的。前一题写过两棵二叉树的等价对吧。那么判断两棵二叉树对称的话,就是把等价算法里面的if(NULL == p || NULL == q ||p->val!=q->val || !isSameTree(p->left,q->left) ||!isSameTree(p->right,q->right) )中的
!isSameTree(p->left,q->left)、!isSameTree(p->right,q->right)
改成 ! isSameTree (p->left,q->right) 、 ! isSameTree(p->right,q->left)
所谓对称,就是对称地等价。
参考C++代码:
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
分析:对称树的左右子树也是相互对称的。前一题写过两棵二叉树的等价对吧。那么判断两棵二叉树对称的话,就是把等价算法里面的if(NULL == p || NULL == q ||p->val!=q->val || !isSameTree(p->left,q->left) ||!isSameTree(p->right,q->right) )中的
!isSameTree(p->left,q->left)、!isSameTree(p->right,q->right)
改成 ! isSameTree (p->left,q->right) 、 ! isSameTree(p->right,q->left)
所谓对称,就是对称地等价。
参考C++代码:
/** * 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(NULL == root) return true; if(NULL == root->left && NULL == root->right) return true; return isMirrorTree(root->left,root->right); } bool isMirrorTree(TreeNode* p, TreeNode* q) { if(NULL == p && NULL == q) return true; if(NULL == p || NULL == q || p->val!=q->val || !isMirrorTree(p->left,q->right) || !isMirrorTree(p->right,q->left) ) return false; return true; } };
相关文章推荐
- [LeetCode]101. Symmetric Tree
- leetcode 101. Symmetric(对称的) Tree
- LeetCode 101. Symmetric Tree
- LeetCode 101. Symmetric Tree
- C++详解Leetcode:101. Symmetric Tree
- LeetCode#101. Symmetric Tree
- <LeetCode OJ> 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 (C++)
- leetcode 101. Symmetric Tree
- leetcode-101. Symmetric Tree
- Leetcode题解 101. Symmetric Tree
- leetcode 101. Symmetric Tree
- leetcode 101. Symmetric Tree对称树(递归和迭代)
- LeetCode——101. Symmetric Tree (bfs)