【LeetCode】Symmetric Tree

Symmetric Tree 
Total Accepted: 13819 Total Submissions: 43667
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

   1
   / \
  2   2
   \   \
   3    3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
【解题思路】
我认为BFS可以很好的解决,当然注意处理空树的情况。
如果左子树或者右子树为空,将当前值赋值为-1,主要是为了防止出现题目中所说的第2种情况。
每层遍历结束之后,将所有值都存放在numList中,从外层到内层,依次推进比较,如果不相等,立刻return false;
直到比较完,一直没有return false,那么就是Symmetric Tree。
Java AC

/**
 * 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;
        }
        return bfs(root);
    }
    public boolean bfs(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> numList = new ArrayList<Integer>();
            while(size > 0){
                size--;
                TreeNode node = queue.peek();
                queue.poll();
                if(node.left != null){
                    numList.add(node.left.val);
                    queue.offer(node.left);
                }else{
                    numList.add(-1);
                }
                if(node.right != null){
                    numList.add(node.right.val);
                    queue.offer(node.right);
                }else{
                    numList.add(-1);
                }
            }
            boolean flag = isSymmetric(numList);
            if(!flag){
                return false;
            }
        }
        return true;
    }
    public boolean isSymmetric(List<Integer> numList){
        int size = numList.size();
        int low = 0;
        int high = size-1;
        while(low < high){
            if(numList.get(low) != numList.get(high)){
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
}

你可能感兴趣的:(【LeetCode】Symmetric Tree)