[Sword refers to the offer brush question] Acwing 39. Symmetric binary tree

ideas

Recursion: determine whether the left and right subtrees are symmetrical --> the left and right children are equal or both are empty
Exit condition: true: the left and right nodes are both empty
false: the values ​​of the left and right nodes are not equal

topic

Please implement a function to determine whether a binary tree is symmetric.

A binary tree is symmetric if it is the same as its mirror image.
Sample

As shown in the figure below, the binary tree [1,2,2,3,4,4,3,null,null,null,null,null,null,null,null] is a symmetric binary tree:
1
/
2 2
/ \ /
3 4 4 3

As shown in the figure below, the binary tree [1,2,2,null,4,4,3,null,null,null,null,null,null] is not a symmetric binary tree:
1
/
2 2
\ /
4 4 3

java code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    
    private boolean mirror(TreeNode r1, TreeNode r2) {
    
    
        if (r1 == null || r2 == null)
            return r1 == null && r2 == null;
        
        if (r1.val != r2.val) return false;
        return mirror(r1.left, r2.right) && mirror(r1.right, r2.left);
    }
    
    public boolean isSymmetric(TreeNode root) {
    
    
        if (root == null) return true;
        return mirror(root.left, root.right);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326228154&siteId=291194637