LeetCode实战:对称二叉树

题目英文

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

题目中文

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

算法实现

/**
 * 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);
}

实验结果

3648525-09077dd6c71ac55e.png
提交记录

相关图文

转载于:https://www.jianshu.com/p/4e8e0301d402

猜你喜欢

转载自blog.csdn.net/weixin_34228662/article/details/91151428