LeetCode combat: Binary Symmetric

English title

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Chinese title

Given a binary tree, check if it is mirror-symmetrical.

For example, a binary tree [1,2,2,3,4,4,3]is symmetrical.

    1
   / \
  2   2
 / \ / \
3  4 4  3

However, the following [1,2,2,null,3,null,3]is not a mirror image:

    1
   / \
  2   2
   \   \
   3    3

Algorithm

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
 
//镜像对称的递归函数
public bool IsMirror(TreeNode t1, TreeNode t2)
{
    if (t1 == null && t2 == null) return true;
    if (t1 == null || t2 == null) return false;
    return (t1.val == t2.val)
        && IsMirror(t1.left, t2.right)
        && IsMirror(t1.right, t2.left);
}

Experimental results

3648525-09077dd6c71ac55e.png
Submit records

Related graphic :

Reproduced in: https: //www.jianshu.com/p/4e8e0301d402

Guess you like

Origin blog.csdn.net/weixin_34228662/article/details/91151428