给定一个二叉树,检查它是否是镜像对称的。
LeetCode 101.对称二叉树
import java.util.*;
class TreeNode{
char data;
TreeNode left;
TreeNode right;
public TreeNode(char data){
this.data=data;
this.right=null;
this.left=null;
}
}
class BiTree{
static int index=0;
public TreeNode CreateTree(String str){
if(index>str.length())
return null;
if(str.charAt(index)=='#')
{
index++;
return null;
}
else
{
TreeNode root= new TreeNode(str.charAt(index));
index++;
root.left=CreateTree(str);
root.right=CreateTree(str);
return root;
}
}
public void Inorder(TreeNode root){
if(root==null)
return;
else
{
Inorder(root.left);
System.out.print(root.data+" ");
Inorder(root.right);
}
}
public void setIndex(){index=0;}
}
public class Main{
public static boolean isSymmetric(TreeNode root){
return check(root,root);
}
public static boolean check(TreeNode p,TreeNode q){
if(p==null && q==null)
return true;
if(p==null || q==null)
return false;
return p.data==q.data && check(p.left,q.right) && check(p.right,q.left);
}
public static void main(String args[]){
Scanner in=new Scanner(System.in);
while(in.hasNext())
{
String s=in.next();
BiTree tree=new BiTree();
TreeNode root=tree.CreateTree(s);
tree.Inorder(root);
System.out.println();
if(isSymmetric(root))
System.out.println("The tree is symmetric!");
else
System.out.println("The tree is not symmetric!");
tree.setIndex();
}
}
}