1 解题思想
这道题是上一道题的延伸版。
首先,题目的意思是说给了一颗树,让我们判断他是否是对称的(以根节点为中心,镜像颠倒而成)
其实解题方式也很简单,把根节点的左右节点开始,当做两个独立的子树,判断这两个子树的是否对称
而判断这两个子树是否对称,就是在判断两个子树的那个算法那里,把原来的左左对比,右右对比,改成左右对比和右左对比就可以了,稍稍改动一下位置就可以
Leetcode 100. Same Tree 验证树是否相同 解题报告
2 原题
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
Note:
Bonus points if you could solve it both recursively and iteratively.
3 AC解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* 当成两棵树遍历检查就可以了
* */
public class Solution {
public boolean check(TreeNode leftPart,TreeNode rightPart){
if(leftPart==null && rightPart==null)
return true;
if(leftPart==null || rightPart==null)
return false;
if(leftPart.val != rightPart.val)
return false;
return check(leftPart.right,rightPart.left) && check(leftPart.left,rightPart.right);
}
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return check(root.left,root.right);
}
}