1 题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
2 解题思路
- 解题方法: 递归
对称二叉树定义: 对于树中 任意两个对称节点 str1 和 str2 ,一定有:str1.val=str2.val :即此两对称节点值相等。
str1.left.val=str2.right.val :即 str1的 左子节点 和 str2 的 右子节点 对称;
str1.right.val=str2.left.val :即 str1 的 右子节点 和 str2 的 左子节点 对称。
根据以上规律,考虑从顶至底递归,判断每对节点是否对称,从而判断树是否为对称二叉树。
复杂度分析:
时间复杂度 O(N) : 其中 N 为二叉树的节点数量,每次执行 recur() 可以判断一对节点是否对称,因此最多调用 N/2 次 isMirror() 方法。
空间复杂度 O(N) : 最差情况下(见下图),二叉树退化为链表,系统使用 O(N) 大小的栈空间。
作者:jyd
链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/solution/mian-shi-ti-28-dui-cheng-de-er-cha-shu-di-gui-qing/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3 解决代码
- 解题方法: 递归 《Java代码》
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//空树认为是对称的
if(root == null){
return true;
}
return isMirror(root.left, root.right);
}
public boolean isMirror(TreeNode tr1, TreeNode tr2){
//当 tr1 和 tr2 同时越过叶节点: 此树从顶至底的节点都对称,因此返回 true
if(tr1 == null && tr2 == null){
return true;
}
//当 tr1 或 tr2中只有一个越过叶节点: 此树不对称,因此返回 false ;
if(tr1 == null || tr2 == null){
return false;
}
//当节点 tr1 值 ! = 节点 tr2 值: 此树不对称,因此返回 false ;
if(tr1.val != tr2.val){
return false;
}
//tr1 的“左右” 子树应该和tr2 的“右左”子树 分别对称
return isMirror(tr1.left, tr2.right) && isMirror(tr1.right, tr2.left);
}
}
- 解题方法: 递归 《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:
def isMirror(tr1, tr2):
if not tr1 and not tr2:
return True
if not tr1 or not tr2:
return False
if tr1.val != tr2.val:
return False
return isMirror(tr1.left, tr2.right) and isMirror(tr1.right, tr2.left)
if not root :
return True
return isMirror(root.left, root.right)