题目描述
给定一个二叉树,检查它是否是镜像对称的。
解题思路
- 递归:当两个节点有相同的值,并且每个树的左子树和另一个树的右子树镜像对称
Cpp实现
/**
* 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;
return isMirror(root->left,root->right);
}
bool isMirror(TreeNode *p,TreeNode *q){
if(p == NULL && q == NULL)
return true;
if(p == NULL || q == NULL)
return false;
return (p->val == q->val) && isMirror(p->left,q->right) && isMirror(p->right,q->left);
}
};
- 时间复杂度:O(n)
Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
def match(l,r):
if not l and not r:
return True
if not l or not r:
return False
return l.val == r.val and match(l.left,r.right) and match(l.right,r.left)
return match(root.left,root.right)
解题思路
- 迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
queue = [root,root]
while queue:
left = queue.pop()
right = queue.pop()
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True
Java实现
//方法以及实现
public class SymmetricTree {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return isMirror(root.left,root.right);
}
public boolean isMirror(TreeNode p,TreeNode q){
if (p == null && q == null)
return true;
if (p == null || q == null)
return false;
return (p.val == q.val) && isMirror(p.left,q.right) && isMirror(p.right,q.left);
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode l1 = new TreeNode(2);
TreeNode l2 = new TreeNode(2);
TreeNode l3 = new TreeNode(3);
TreeNode l4 = new TreeNode(4);
TreeNode l5 = new TreeNode(4);
TreeNode l6 = new TreeNode(3);
root.left = l1;
root.right = l2;
root.left.left = l3;
root.left.right = l4;
root.right.left = l5;
root.right.right = l6;
Solution solution = new Solution();
boolean bool = solution.isSymmetric(root);
System.out.println(bool);
}
}
- 时间复杂度:O(n)