一晃一个月没写博客了,时间总是悄悄的向前啊。
二叉树与链表的结合,二叉树与链表都是递归的宠儿。
二叉树与链表问题是天然的递归问题,只有直击问题本质方能立于不败之地。
这次给大家带来一道二叉树的中等题,也不难,就是练习练习递归,写的玩玩,练练手吧。
题目一看完,心中大致框架就有了,分两步,第一步遍历树,只要树节点值等于链表的第一个节点的值,那就得开始匹配了吧,看看能不能匹配的上。
第一步:树的遍历,闭着眼睛也能写吧。
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);
}
}