101. Symmetric对称 Tree

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

 

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

 
需要左右对称,解题思路和Same Tree类似。
如果拿掉root结点的话,逻辑其实相当于是比较root.left和root.right是否same tree类似的逻辑。只是需要把之前的left.left和right.right比较,left.right和right.left进行比较。
 
复制代码
 public bool IsSymmetric(TreeNode root)
        {
            return IsMirror(root?.left, root?.right);
        }

        public bool IsMirror(TreeNode left, TreeNode right)
        {
            bool flag;
            if (left == null && right == null)
            {
                flag = true;
            }
            else if (left == null || right == null)
            {
                flag = false;
            }
            else
            {
                if (left.val == right.val)
                {
                    flag = IsMirror(left.left, right.right) && IsMirror(left.right, right.left);
                }
                else
                {
                    flag = false;
                }
            }

            return flag;
        }
复制代码

 

 
 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(150)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-03-18 ASP.NET MVC 4 Content Map
2016-03-18 ASP.NET Overview
2016-03-18 ASP.NET 4 and Visual Studio 2010
2015-03-18 QuickStart下的CommandFilter项目 github上自己修改过的版本
2015-03-18 演练:实现支持基于事件的异步模式的组件
点击右上角即可分享
微信分享提示