[LeetCode-Java Exercise] 101. Symmetric Binary Tree (Simple)

1. Title description

Insert picture description here

2. Problem solving ideas

Recursion
Ideas and Algorithms
If the left subtree and the right subtree of a tree are mirrored and symmetrical, then the tree is symmetrical.
Insert picture description here
Therefore, the question can be transformed into: Under what circumstances are the two trees mirror images of each other?
If the following conditions are met at the same time, the two trees are mirror images of each other:
their two root nodes have the same value
. The right subtree of each tree is mirrored and symmetrical with the left subtree of the other tree.
Insert picture description here
We can implement such a recursive function. , Traverse the tree by "synchronizing the movement" of the two pointers. Both the p pointer and the q pointer point to the root of the tree at the beginning. Then when p moves to the right, q moves to the left, and when p moves to the left, q moves to the right. . Check each time whether the values ​​of the current p and q nodes are equal, and if they are equal, judge whether the left and right subtrees are symmetric.

3. Code implementation

class Solution {
    
    
    public boolean isSymmetric(TreeNode root) {
    
    
        return check(root, root);
    }

    public boolean check(TreeNode p, TreeNode q) {
    
    
        if (p == null && q == null) {
    
    
            return true;
        }
        if (p == null || q == null) {
    
    
            return false;
        }
        return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
    }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/114233956