判断对称二叉树

题目描述

请实现一个函数,用来判断一棵二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
 

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

题目分析

如果对第二种情况遍历得到的输出结果与对它的镜像二叉树遍历得到的输出结果相同。

但是第二种情况不是对称二叉树。

考虑在null位置补加“#”。

 采用层序遍历。左:1,2,2,#,3,#,3;右:1,2,2,3,#,3,#。这样通过比较两个字符串就可以判断一个二叉树与其镜像二叉树

 

是否相等。

 

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
   
    String  str = new String("");
    
     void tran1(TreeNode root) {
        if (root != null) {
            str=str.concat(String.valueOf(root.val));
            tran1(root.left);
            tran1(root.right);
        }else{
            str=str.concat("#");
        }
    }
     void tran2(TreeNode root) {
        if (root != null) {
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            tran2(root.left);
            tran2(root.right);
        }
    }
       
    
    boolean isSymmetrical(TreeNode pRoot)
    {
       tran1(pRoot);
        String str1 = new String("");
        str1 = str;
        str = "";
        
        tran2(pRoot);
        tran1(pRoot);
        String str2 = new String("");
        str2 = str;
        return str1.equals(str);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-06-28 22:00  ofmou  阅读(416)  评论(0)    收藏  举报