三刷101. Symmetric Tree

Easy

recursive method,要对称要注意几点:

  • root.left.val = root.right.val
  • root.left的左子树要和root.right的右子树对称
  • root.right的左子树要和root.left的右子树对称
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        return helper(root.left, root.right);
    }
    
    private boolean helper(TreeNode l, TreeNode r){
        if (l == null && r == null){
            return true;
        }
        if (l == null || r == null){
            return false;
        }
        return l.val == r.val && helper(l.left, r.right) && helper(l.right, r.left);        
    }
}

这道题要保证iterative的也会写:要注意while循环里当leftTemp == null && rightTemp == null的时候是continue继续检查下面的,而不是直接返回true.比如下面这个例子:


三刷101. Symmetric Tree_第1张图片
image.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        Queue queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);
        while (!queue.isEmpty()){
            TreeNode leftTemp = queue.poll();
            TreeNode rightTemp = queue.poll();
            if (leftTemp == null && rightTemp == null){
                continue;
            }
            if (leftTemp == null || rightTemp == null){
                return false;
            }
            if (leftTemp.val != rightTemp.val){
                return false;
            }
            queue.offer(leftTemp.left);
            queue.offer(rightTemp.right);
            queue.offer(leftTemp.right);
            queue.offer(rightTemp.left);
        }
        return true;
    }
}

你可能感兴趣的:(三刷101. Symmetric Tree)