剑指offer——对称二叉树判断
1 题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
2 我的错误解答
思路:利用二叉树中序遍历和对称中序遍历相等来解决该问题。
错误原因:中序遍历中输出序列存入到数组中出现错误!
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.LinkedList;
public class Solution {
LinkedList<TreeNode> list1=new LinkedList<TreeNode>();
LinkedList<TreeNode> list2=new LinkedList<TreeNode>();
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot==null){
return true;
}
//LinkedList<TreeNode> list1=midOrder1(pRoot);
//LinkedList<TreeNode> list2=midOrder2(pRoot);
list1=midOrder1(pRoot);
list2=midOrder2(pRoot);
if(list1.size() != list2.size()){
return false;
}
for(int i=0;i<list1.size();i++){
if(list1.get(i)!=list2.get(i)){
return false;
}
}
return true;
}
public LinkedList<TreeNode> midOrder1(TreeNode pRoot){
//LinkedList<TreeNode> list2=new LinkedList<TreeNode>();
if(pRoot!=null){
midOrder1(pRoot.left);
list1.add(pRoot);
midOrder1(pRoot.right);
}
return list1;
}
public LinkedList<TreeNode> midOrder2(TreeNode pRoot){
//LinkedList<TreeNode> list2=new LinkedList<TreeNode>();
if(pRoot!=null){
midOrder2(pRoot.right);
list2.add(pRoot);
midOrder2(pRoot.left);
}
return list2;
}
}
改用常用数组,通过率也为0:
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot==null){
return true;
}
midOrder1(pRoot);
midOrder1(pRoot);
if(i!=j){
return false;
}
for(int k=0;k<i;k++){
if(arr1[k]!=arr2[k]){
return false;
}
}
return true;
}
int i=0;
int arr1[]=new int[1000];
public void midOrder1(TreeNode pRoot){
if(pRoot!=null){
midOrder1(pRoot.left);
arr1[i++]=pRoot.val;
midOrder1(pRoot.right);
}
//return arr1[i];
}
int j=0;
int[] arr2=new int[1000];
public void midOrder2(TreeNode pRoot){
if(pRoot!=null){
midOrder2(pRoot.left);
arr2
[j++]=pRoot.val;
midOrder2(pRoot.right);
}
//return arr2[j];
}
}
您的代码已保存
答案错误:您提交的程序没有通过所有的测试用例
case通过率为0.00%
测试用例:
{8,6,6,5,7,7,5}
对应输出应该为:
true
你的输出为:
false
3 书上的解法:不保存节点值,直接根据前序遍历以及对称前序遍历序列相等符合题意,在遍历过程中比较并返回
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
if(pRoot==null){
return true;
}
return isSymmetrical(pRoot,pRoot);
}
public boolean isSymmetrical(TreeNode pRoot1,TreeNode pRoot2){
if(pRoot1==null && pRoot2==null){//考虑节点都为null的情况
return true;
}
if(pRoot1==null || pRoot2==null){//该情况为一个为null,另一个不为null
return false;
}
if(pRoot1.val!=pRoot2.val){
return false;
}//该情况为值不相等,返回false
return isSymmetrical(pRoot1.left,pRoot2.right) && isSymmetrical(pRoot1.right,pRoot2.left);
}
}