思路
DFS,先将链表转换为字符串s在进行匹配
解题过程
对二叉树进行遍历,每到一个新节点判断当前的字符串t长度是否大于等于的长度,如果满足,再将t从末尾截取s.length()长度的子串与s进行匹配,若匹配成功,结果为true,直到遍历完整棵树
Code
/*** 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 {String s = "";int len=0;boolean ans=false;public boolean isSubPath(ListNode head, TreeNode root) {while(head!=null){s+=head.val;head=head.next;}len=s.length();dfs(root,"");return ans;}public void dfs(TreeNode root, String t) {if (root == null)return;t += root.val;if (t.length()>=len&&t.substring(t.length()-len,t.length()).equals(s))ans=true;dfs(root.left, t);dfs(root.right, t);}
}作者:菜卷
链接:https://leetcode.cn/problems/linked-list-in-binary-tree/solutions/3034306/er-cha-shu-zhong-de-lian-biao-by-ashi-ji-hh3t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。