leetcode第五题 sametree 深度搜索

博客围绕判断两个二叉树是否相同展开,指出若结构相同且节点值相同则两树相同。采用深度搜索法,只要有一个分支不对称,两树就不同。通过debug可知搜索顺序,且利用语言特性实现了深度搜索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

这个题目利用深度搜索去做,因为只要发现有一个分支不对称,那么就可以判断这两个二叉树不相同

#include <iostream>
using namespace std;
//////链表的节点创建,创建一个节点/////////
struct TreeNode {
       int val;
       TreeNode *lp;
       TreeNode *rp;
       TreeNode();
       TreeNode(int a){val=a;lp=NULL;rp=NULL;};   ////这里创建一个结构体的构造函数,很方便,初始化的时候直接进行初始化
     };

bool isSameTree(TreeNode* p, TreeNode* q) {
    if (p == NULL && q == NULL) return true;  ////当搜索到最底层的时候,返回true
    if (p == NULL || q == NULL) return false;
    if (p->val != q->val) return false;  /////
    return isSameTree(p->lp, q->lp) && isSameTree(p->rp, q->rp); ///这种情况实际上是p和q的val相同的情况,那么就继续比较他们的左右子树,
}

int main() {
    TreeNode *a = new TreeNode(1);
    TreeNode *b = new TreeNode(2);
    TreeNode *c = new TreeNode(3);
    TreeNode *d = new TreeNode(4);
    TreeNode *e = new TreeNode(5);
    TreeNode *f = new TreeNode(6);

    TreeNode *a1 = new TreeNode(1);
    TreeNode *b1 = new TreeNode(2);
    TreeNode *c1= new TreeNode(3);
    TreeNode *d1 = new TreeNode(4);
    TreeNode *e1 = new TreeNode(5);
    TreeNode *f1 = new TreeNode(6);

    a->lp = b;
    a->rp = c;
    b->lp = d;
    b->rp = e;
    c->lp = f;

    a1->lp = b1;
    a1->rp = c1;
    b1->lp = d1;
//    b1->rp = e1;
    c1->lp = f1;
    isSameTree(a,a1);


    return 0;
}

这里我做的二叉树是这样的:

 

 

输入两个二叉树:

    1          1
   / \        / \
  2   3      2   3

  /      \      /         /      /

4       5   6       4      6   

通过debug发现,一次搜索的顺序是1,2,4,5 然后就结束了,

说明当 return A&&B的时候,只要确认A是false,那么就没必要再计算B了,但是如果A是true的话,此时无法确认返回值,则需要继续计算B,正是因为语言有这样的功能,才正真实现了,深度搜索。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白码思

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值