代码改变世界

leetcode-0101 symmetric-tree

2022-05-31 21:14  jetwill  阅读(16)  评论(0编辑  收藏  举报

https://leetcode.cn/problems/symmetric-tree/

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1:

Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:

Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints:

The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100

Follow up: Could you solve it both recursively and iteratively?

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root){
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        TreeNode L = root.left;
        TreeNode R = root.right;
        if(root == null || L == null && R == null){
            return true;
        }
        q.add(L);
        q.add(R);
        while(!q.isEmpty()){
            L = q.remove();
            R = q.remove();
            if(L == null && R == null){
                continue;
            }
            if( (L == null || R == null) || (L.val != R.val) ){
                return false;
            }
            q.add(L.left);
            q.add(R.right);

            q.add(L.right);
            q.add(R.left);

        }
        return true;
    }
    // public boolean isSymmetric(TreeNode root) {
    //     if(root == null){
    //         return true;
    //     }
    //     //invoke the recursive function to compare the left subtree and the right subtree
    //     return deepCheck(root.left, root.right);        
    // }

    private boolean deepCheck(TreeNode left, TreeNode right){
        //Conditions to exit: both are null
        //or either is null
        //or vavlues of two node are unequal
        if(left == null && right == null){
            return true;
        }
        if(left == null || right == null){
            return false;
        }
        if(left.val != right.val){
            return false;
        }
        //compare recursivly, left child of left vs right child of right,
        //and right child of left vs left child of right
        return deepCheck(left.left, right.right) && deepCheck(left.right, right.left);
    }
}