[LeetCode] 100. Same Tree

本文探讨了如何通过深度优先搜索和递归方法,来判断两棵二叉树是否完全相同,包括节点值和结构的一致性。通过具体示例和代码实现,详细解释了解决方案。

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

原题链接:https://leetcode.com/problems/same-tree/

1. 题目介绍

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:
在这里插入图片描述
Example 2:
在这里插入图片描述
Example 3:
在这里插入图片描述

2. 解题思路

深度优先搜索 + 递归
DFS搜索,沿着深度优先搜索的方法,逐一遍历节点,如果遇到不相同的节点就返回false。
实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q != null){
            return false;
        }
        if(p != null && q == null){
            return false;
        }
        if(p == null && q == null){
            return true;
        }
        if(p.val != q.val){
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right,q.right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值