题目描述
// 28. 对称的二叉树
// 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一
// 棵二叉树和它的镜像一样,那么它是对称的。
// 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
// 1
// / \
// 2 2
// / \ / \
// 3 4 4 3
// 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
// 1
// / \
// 2 2
// \ \
// 3 3
题解
// 还记得在《26. 树的子结构》这道题中,我们需要找到B数是不是A的子树,
// 需要逐个结点遍历B树判断是不是和A相同。本题有异曲同工之妙,
// 只是需要遍历的树变成了自己本身,给定一个树root,
// 我们需要同时遍历root的左树和右树,在左树遍历点和右树遍历点中
// 我们需要判断:
// 1.左子树遍历点和右子树遍历点是不是相等,
// 2.左子树的左子树点与右子树的右子树点是不是相等,
// 3.左子树的右子树点与右子树的左子树点是不是相等。
// 力扣
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:36.4 MB, 在所有 Java 提交中击败了74.58%的用户
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
return recur(root, root);
}
private boolean recur(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
return false;
if (root2.val != root1.val)
return false;
return (recur(root1.left, root2.right) && recur(root1.right, root2.left));
}
}
// 牛客
// 运行时间:11ms
// 占用内存:9652k
public class Solution {
boolean isSymmetrical(TreeNode pRoot) {
if (pRoot == null)
return true;
return recur(pRoot, pRoot);
}
private boolean recur(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
return false;
if (root1.val != root2.val)
return false;
return recur(root1.left, root2.right) && recur(root1.right, root2.left);
}
}