跳至正文
-
Subscribe to our newsletter & never miss our best posts. Subscribe Now!
小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

小奥的学习笔记

万丈高楼平地起,勿在浮沙筑高台

  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
  • 首页
  • Sample Page
  • 隐私策略
  • GuestBook
  • 慕课课程(MOOC’s Lessons)
  • Footprints
  • About Me
  • 个人履历
关

搜索

  • https://www.facebook.com/
  • https://twitter.com/
  • https://t.me/
  • https://www.instagram.com/
  • https://youtube.com/
Subscribe

题目描述

Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

思路说明

其实这个题非常简单,算是判断一个树是不是另一个树子树的基础版,不需要调用另一个子程序,直接递归自己这个程序即可。就是判断树上每一个结点当前的情况:

  • p当前节点为空且q当前节点为空,true;
  • p为空q不为空,或q为空p不为空,false;
  • p->val==q->val,那么就判断它的左右子树;
  • p->val!q->val,false。

判断完成后,逐层向上返回bool结果。

代码实现

    bool isSameTree(TreeNode *p, TreeNode *q) {
        if(p==nullptr && q==nullptr)
            return true;
        if(p==nullptr || q==nullptr)
            return false;
        if(p->val==q->val)
            return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
        else
            return false;
    }

标签:

leetcode
作者

yszhang

关注我
其他文章
上一个

[leetcode]populating next right pointers in each node

下一个

[leetcode]roman to integer(罗马数字转整数)

暂无评论!成为第一个。

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Copyright 2026 — 小奥的学习笔记. All rights reserved. Blogsy WordPress Theme