当前位置:网站首页>February 13, 2022-4-symmetric binary tree

February 13, 2022-4-symmetric binary tree

2022-07-05 23:01:00 Procedural ape does not lose hair 2

Give you the root node of a binary tree root , Check whether it is axisymmetric .

Example 1:
 Insert picture description here

Input :root = [1,2,2,3,4,4,3]
Output :true
Example 2:
 Insert picture description here

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

Tips :

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

java Code :

/**
 * 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) {
        return check(root, root);
    }

    // Method 1   recursive 
    // private boolean check(TreeNode r1, TreeNode r2) {
    //     if(r1 == null && r2 == null) {
    //         return true;
    //     }

    //     if(r1 == null || r2 == null || r1.val != r2.val) {
    //         return false;
    //     }

    //     return check(r1.left, r2.right) && check(r1.right, r2.left);
    // }

    // Method 2  iteration 
    private boolean check(TreeNode r1, TreeNode r2) {
          Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(r1);
        q.offer(r2);

        while ( !q.isEmpty()) {
            r1 = q.poll();
            r2 = q.poll();

            if(r1 == null && r2 == null) {
                continue;
            }

            if( r1== null || r2 == null || r1.val != r2.val) {
                return false;
            }

            q.offer(r1.left);
            q.offer(r2.right);

            q.offer(r2.left);
            q.offer(r1.right);

        }

        return true;
    }


}
原网站

版权声明
本文为[Procedural ape does not lose hair 2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140348289290.html