`
blue2048
  • 浏览: 183057 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Symmetric Tree - java

阅读更多
/**

 * Definition for binary tree

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

      public boolean isSymmetric(TreeNode root) {

        if(root==null){

            return true;

        }

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();

        LinkedList<TreeNode> childrenQueue = new LinkedList<TreeNode>();

        queue.add(root);

        while (!queue.isEmpty()){

            TreeNode node = queue.remove();

            if(node==null || node.left==null){

                childrenQueue.add(null);

            }else{

                childrenQueue.add(node.left);

            }

            if(node==null || node.right==null){

                childrenQueue.add(null);

            }else{

                childrenQueue.add(node.right);

            }

            if(queue.isEmpty() && !childrenQueue.isEmpty()){

                for(int i=0; i<childrenQueue.size(); i++){

                     if(childrenQueue.get(i)!=null){

                        queue.add(childrenQueue.get(i));

                    }

                    if(i<childrenQueue.size()/2){

                        int j = childrenQueue.size()-i-1;

                        if(childrenQueue.get(i)==null && childrenQueue.get(j)==null){

                            continue;

                        }

                        if((childrenQueue.get(i)==null && childrenQueue.get(j)!=null) || (childrenQueue.get(i)!=null && childrenQueue.get(j)==null)){

                            return false;

                        }

                         if(childrenQueue.get(i).val == childrenQueue.get(j).val){

                            continue;

                        }

                        return false;

                    }

                  

                }

                childrenQueue.clear();

            }

        }

        return true;

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics