LeetCode - Same Tree

题注

不能再刷了,再刷天亮了… 今天最后一道,今天还要看看论文呢,毕竟Paper才是王道啊!

题目

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.

分析

这道题本身其实真的挺简单的:分别先判断节点是否全为空或者全为非空且value相同。如果是,则递归判断左右节点是否相同,如果都满足则返回true,否则返回false。

但是这道题我前面提交了好几次都是错的,原因是我多想了一个事情:两个树左左节点和右右节点相同则树相同,那么两个树左右节点和右左节点相同,这两个树是否相同呢?我认为是相同的,但是LeetCode认为是不同的。仔细观察题目,题目中说的是they are structurally identical,因此这种对称树非相同的要求便可以理解了。

错误代码如下:

/**
 * 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;
        }
        if (p == null || q == null){
            return false;
        }
        if (p.val != q.val){
            return false;
        }
        boolean isSameLLTree = isSameTree(p.left, q.left);
        boolean isSameRRTree = isSameTree(p.right, q.right);
        if (isSameLLTree && isSameRRTree){
            return true;
        }
        boolean isSameLRTree = isSameTree(p.left, q.right);
        boolean isSameRLTree = isSameTree(p.right, q.left);
        if (isSameLRTree && isSameRLTree){
            return true;
        }
        return false;
    }
}

此代码LeetCode会在第49个test返回错误。如果我们将最后的一个判断删除,那么代码就可以Accepted了。

代码

/**
 * 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;
        }
        if (p == null || q == null){
            return false;
        }
        if (p.val != q.val){
            return false;
        }
        boolean isSameLLTree = isSameTree(p.left, q.left);
        boolean isSameRRTree = isSameTree(p.right, q.right);
        if (isSameLLTree && isSameRRTree){
            return true;
        }else{
            return false;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值