高效解决二叉树与链表问题,直击递归本质。

一晃一个月没写博客了,时间总是悄悄的向前啊。
二叉树与链表的结合,二叉树与链表都是递归的宠儿。
二叉树与链表问题是天然的递归问题,只有直击问题本质方能立于不败之地。
这次给大家带来一道二叉树的中等题,也不难,就是练习练习递归,写的玩玩,练练手吧。
在这里插入图片描述

在这里插入图片描述
题目一看完,心中大致框架就有了,分两步,第一步遍历树,只要树节点值等于链表的第一个节点的值,那就得开始匹配了吧,看看能不能匹配的上。

第一步:树的遍历,闭着眼睛也能写吧。

void dfs(TreeNode root,ListNode head){
        if(root==null) return;
        if(root.val==head.val){
            if(f(root.left,head.next)||f(root.right,head.next)){
                flag=true;
                return;
            } 
        }
        dfs(root.left,head);
        dfs(root.right,head); 
    }

第二步:怎么去比较链表和树是否匹配呢?
分析一波,当前树节点值等于链表第一个节点的值。树节点可选左右节点,链表只能选下一个节点,发现没?问题是相同的,只是规模变小了,那说明递归可以解决问题了。

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

最后放上整体代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    boolean flag;
    public boolean isSubPath(ListNode head, TreeNode root) {
        dfs(root,head);
        return flag;
    }

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

    }

    void dfs(TreeNode root,ListNode head){
        if(root==null) return;
        if(root.val==head.val){
            if(f(root.left,head.next)||f(root.right,head.next)){
                flag=true;
                return;
            } 
            
        }
        dfs(root.left,head);
        dfs(root.right,head); 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值