100. Same Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

 

二叉树有三种遍历方式,先序遍历,中序遍历以及后序遍历

采用中序遍历,进行逐结点进行比较

只要写出比较一个结点的方法就可以,然后递归调用左右子结点。

复制代码
 public bool IsSameTree(TreeNode p, TreeNode q)
        {
            bool flag;
            if (p == null && q == null)
            {
                flag = true;
            }
            else if (p == null || q == null)
            {
                flag = false;
            }
            else
            {
                if (p.val == q.val)
                {
                    flag = IsSameTree(p.left, q.left) && IsSameTree(p.right, q.right);
                }
                else
                {
                    flag = false;
                }

            }
            return flag;
        }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-03-14 pass an instance of class to TestCase as parameter
2018-03-14 How to Integrate .NET Projects with Jenkins
2016-03-14 Knowing When to Use Override and New Keywords (C# Programming Guide)
2016-03-14 Versioning with the Override and New Keywords (C# Programming Guide)
2016-03-14 Polymorphism (C# Programming Guide)
2015-03-14 2-Medium下的MultipleCommandAssembly
2015-03-14 如何获取supersocket的源代码
点击右上角即可分享
微信分享提示