前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:101. Symmetric Tree

LeetCode笔记:101. Symmetric Tree

作者头像
Cloudox
发布2021-11-23 14:12:55
1220
发布2021-11-23 14:12:55
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

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:

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

image.png Note: Bonus points if you could solve it both recursively and iteratively.

大意:

给出一个二叉树,检查它是否是自己的镜像(中心对称)。 比如,二进制数 [1,2,2,3,4,4,3] 是对称的

image.png 但 [1,2,2,null,3,null,3] 就不是:

image.png 注意: 如果可以用递归和迭代来做会加分

思路:

这道题我没想出来,总觉得要递归地去比较中间那么多数字是不是对称的不好做到,看了看别人的做法,还是很简单的,只能怪自己没想明白,想得太复杂了。

先检查root啊、左右子节点啊是不是null这些情况直接作出判断,然后用递归去做,每次检查一个节点的左子节点的左子节点和右子节点的右子节点以及左子节点的右子节点和右子节点的左子节点是不是一样的,就可以判断了。听起来有点绕,其实想一想就能明白了,我们总是去对一个节点的左右两个子节点去往下比较,这样就会越往下比较的越开,并不会出现单纯的相邻节点之间进行比较而已。

他山之石:

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        else return isMirror(root.left, root.right);
    }
    
    public boolean isMirror(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        else if (left == null || right == null) return false;
        else return (left.val == right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left);
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 他山之石:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档