题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
示例1
输入
{8,6,6,5,7,7,5}
返回值
true
示例2
输入
{8,6,9,5,7,7,5}
返回值
false
解题思路
最暴力的方法--先将树进行前序遍历存储结构,再将树进行求镜像,再对镜像树进行前序遍历,比较遍历结果(如果节点值都一样,则不行--通过90%的用例)
参考官方题解的最大的收获:找规律递归可以想到,但是因为一个根节点只有一棵树,下边有二棵子树,所以思路受限--可以用两个树来比较
具体过程如下图官方题解
java代码--注释的为暴力解法
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.*;
public class Solution {
boolean isSame(TreeNode root1,TreeNode root2){
if(root1==null && root2==null) return true;
if(root1==null || root2==null) return false;
return root1.val==root2.val && isSame(root1.left,root2.right) && isSame(root2.left,root1.right);
}
boolean isSymmetrical(TreeNode pRoot){
return isSame(pRoot,pRoot);
}
// boolean isSymmetrical(TreeNode pRoot)
// {
// if(pRoot==null) return true;
// boolean ans=true;
// ArrayList<Integer> before=new ArrayList<Integer>();
// ArrayList<Integer> after=new ArrayList<Integer>();
// order(pRoot,before);
// Mirror(pRoot);
// order(pRoot,after);
// for(int i=0;i<before.size();i++){
// if(before.get(i)!=after.get(i)){
// ans=false;
// }
// }
// return ans;
// }
// public void order(TreeNode root,ArrayList<Integer> list){
// if(root==null) return;
// list.add(root.val);
// order(root.left,list);
// order(root.right,list);
// }
// public void Mirror(TreeNode root){
// if(root==null) return;
// if(root.left != null || root.right !=null){
// Mirror(root.left);
// Mirror(root.right);
// TreeNode tmp=root.left;
// root.left=root.right;
// root.right=tmp;
// }
// }
}
京公网安备 11010502036488号