[LeetCode]Same Tree

本文介绍了一种检查两棵二叉树是否等价的方法,通过递归比对每个节点来确保它们结构相同且节点值相等。同时,文章还讨论了在实现过程中常见的编译错误,如unreachable statement,并提供了正确的解决方案。

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

题目:

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.

代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q==null)
            return true;
        else if(q!=null && p!=null){
            if(p.val==q.val){ 
                return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
            }
            else return false;
        }
        else
            return false;
    }
}

出现的错误:

在(p.val==q.val)条件下,曾写成了

 return isSameTree(p.left,q.left); 

return isSameTree(p.right,q.right);

编译错误,unreachable statement。因为一个条件下,写了两个return啊!!!! 

出现unreachable statement 错误的可能有:

(1)在reutrn语句后写语句。

(2)在throw语句后写语句。

(3)break、continue语句之后定义语句。

(4)“\u10100”//合法,相当于‘\u1010’和字符串“0”。

(5)移位运算符可以用于long int char short byte。

(6)类的访问控制符可以是public或什么都不加。

(7)goto是保留字但不是关键字。then什么都不是。

(8)把超类的类型强制转换后赋给子类的对象时,编译无异常,但运行时会出现异常。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值