题目
Given the root of a binary tree,check whether it is a mirror of itself(i.e.,symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
解法一:递归(深度周游)
思路和算法
如果一个树的左子树和右子树镜像对称,那么这个树是对称的。
因此,该问题可以转化为:两个树在什么情况下互为镜像?
如果同事满足下面的条件,两个树互为镜像:
- 它们的两个根节点具有相同的值。
- 每个树的右子树都与另一个树的左子树镜像对称。
我们可以实现这样一个递归函数,通过【同步移动】两个指针的方法来遍历这棵树,p指针和q指针一开始都指向这颗树的根,随后p右移,q左移,p左移,q右移。每次检查当前p和q节点的值是否相等,如果相等再判断左右子树是否对称。
代码
/**
* 方法二:迭代(队列)(广度周游)
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution2 {
public boolean isSymmetric(TreeNode root) {
return checkIsSymmetric(root, root);
}
public boolean checkIsSymmetric(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && checkIsSymmetric(p.left, q.right) && checkIsSymmetric(p.right, q.left);
}
}
方法二:迭代(队列)(广度周游)
思路和算法
我们引入一个队列,这是把递归程序改写成迭代程序的常用方法。初识化时我们把根节点入队两次。每次提取两个结点并比较他们的值(队列中每两个连续的结点应该是相等的,而且他们的子树互为镜像),然后将两个结点的左右子结点按相反的顺序插入队列中。当队列为空时,或者我们检测到树不对称(即从队列中取出两个不相等的连续结点)时,该算法结束。
代码
/**
* 树的广度优先遍历
*
* @author aiwenwen
* @date 20:33 2022/6/4
**/
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
}
转载
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/symmetric-tree/solution/dui-cheng-er-cha-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。