刷题小记 (7) LeetCode 1367 二叉树中的列表

LeetCode 1367

2020.8.13

我的通过代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubPath(ListNode head, TreeNode root) {
        if(head==null) return true;
        if(root==null) return false;
        return judge(head,root)||isSubPath(head,root.left)||isSubPath(head,root.right);

    }

    boolean judge(ListNode head, TreeNode root) {
        if(head==null) return true;
        if(root==null) return false;
        if(head.val!=root.val) return false;
        else {
            return judge(head.next,root.left)||judge(head.next,root.right);
        }
    }
}

碰上的问题

这次出现的问题应该是很典型的递归问题,一开始我写的代码是这样的:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubPath(ListNode head, TreeNode root) {
        if(head==null) return true;
        if(root==null) return false;
        if(head.val==root.val) {
            return isSubPath(head.next,root.left)||isSubPath(head.next,root.right);
        } else {
            return isSubPath(head,root.left)||isSubPath(head,root.right);
        }

    }
}

看起来很有道理,但还是忽略了一些情况,没有办法让二叉树的每一个节点都有作为头节点的机会,举个例子:

[1,2,1,2,4]
[1,null,2,null,1,null,2,null,1,null,2,null,4]

这样一棵只有左子树的二叉树,前四个节点都可以与链表的前四个元素匹配,可程序发现最后一个节点的值1不等于链表的最后一个节点的值4时,程序已经无法再回到二叉树的第二个节点了,只能从第五个节点开始继续往下匹配,这样一来就漏掉了好多可能性,少了很多情况,导致最后的结果不正确。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值