[编程题]对称的二叉树

来源:互联网 发布:突破网络系统的第一步 编辑:程序博客网 时间:2024/06/06 04:16

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

/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*///将二叉树“补成”完全二叉树,利用中序遍历来查看两边的节点是否对称。import java.util.ArrayList;import java.util.Iterator;public class Solution {     ArrayList<Integer> in= new ArrayList<Integer>();    boolean isSymmetrical(TreeNode pRoot)    {            if(pRoot==null){                return true;            }            else{                middle(pRoot);                Iterator it =in.iterator();                int []array=new int[in.size()];                int index=0;                while(it.hasNext()){                    array[index]=(Integer) it.next();                    index++;                }                    for(int i=0;i<array.length/2;i++){                        if(array[i]!=array[array.length-1-i]){                            return false;                        }                    }            }            return true;    }     public void middle(TreeNode pRoot){            if(pRoot.left!=null){                middle(pRoot.left);            }            if((pRoot.left==null&&pRoot.right!=null)){                in.add(0);            }            in.add(pRoot.val);            if((pRoot.left!=null&&pRoot.right==null)){                in.add(0);            }            if(pRoot.right!=null){                middle(pRoot.right);            }        }}
0 0