LeetCode 51 Symmetric Tree

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.

分析:

递归解法就是分别判断左右子树是否对称,即左子树的左子树和右子树的右子树应该是对称的,左子树的右子树和右子树的左子树应该是对称的。

/**
 * 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 isSymmetric(root.left, root.right);
    }
    private boolean isSymmetric(TreeNode left, TreeNode right){
        if(left==null) return right==null;
        if(right==null) return false;
        if(left.val != right.val) return false;
        if(!isSymmetric(left.left, right.right)) return false;
        if(!isSymmetric(left.right, right.left)) return false;
        
        return true;
    }
}
迭代解法

就是分别对左右子树进行层序遍历,对于每一层,左子树从左向右遍历,右子树从右向左遍历,保证左右队列里每一个元素都相等,则是对称的。

/**
 * 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;
        Queue<TreeNode> left = new LinkedList<TreeNode>();
        Queue<TreeNode> right = new LinkedList<TreeNode>();
        left.add(root.left);
        right.add(root.right);
        while(left.size()>0 && right.size()>0){
            TreeNode l = left.remove();
            TreeNode r = right.remove();
            if((l == null && r != null) || (l != null && r == null))
                return false;
            if(l != null && r != null){
                if(l.val != r.val) return false;
                left.add(l.left);
                left.add(l.right);
                right.add(r.right);
                right.add(r.left);
            }
        }
        return true;
    }
}



你可能感兴趣的:(LeetCode,递归,二叉树,迭代,对称二叉树)