LeetCode //C - 101. Symmetric Tree

101. 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:

insert image description here

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

Example 2:

insert image description here

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

From: LeetCode
Link: 101. Symmetric Tree


Solution:

Ideas:
  1. Check if the root is null. If it’s null, then the tree is symmetric.
  2. Otherwise, check if the left subtree of the root is a mirror image of the right subtree.

To check if two trees are mirror images of each other:

  1. If both trees are null, return true.
  2. If one tree is null and the other isn’t, return false.
  3. If the values of the root nodes of the two trees are not the same, return false.
  4. Recursively check if the left subtree of the first tree is a mirror image of the right subtree of the second tree and vice versa.
Code:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isMirror(struct TreeNode* t1, struct TreeNode* t2) {
    
    
    if (t1 == NULL && t2 == NULL) return true;
    if (t1 == NULL || t2 == NULL) return false;
    return (t1->val == t2->val)
        && isMirror(t1->right, t2->left)
        && isMirror(t1->left, t2->right);
}

bool isSymmetric(struct TreeNode* root) {
    
    
    return isMirror(root, root);
}

Guess you like

Origin blog.csdn.net/navicheung/article/details/132683499