算法:判斷二叉樹是否包含鏈表Linked List in Binary Tree

題目

1367. Linked List in Binary Tree
Given a binary tree root and a linked list with head as the first node.

Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.

Example 1:

在這裏插入圖片描述

Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
​
Output: true
​
Explanation: Nodes in blue form a subpath in the binary Tree.  

Example 2:
在這裏插入圖片描述

Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]​
Output: true

Example 3:

Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
Output: false
Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.

Constraints:

1 <= node.val <= 100 for each node in the linked list and binary tree.

The given linked list will contain between 1 and 100 nodes.

The given binary tree will contain between 1 and 2500 nodes.

解題

解決思路:這裏用到兩個深度優先遍歷。

  1. 重點的思維應該是鏈表爲主,比如鏈表第一個就是對的,那麼就用樹的深度優先遍歷dfs繼續判斷(注意:樹是下個結點左右子樹是或的關係,只要一個是對的,那麼結果是對的),整個鏈表是否都是對的,如果是對的,則直接返回結果。
  2. 如果鏈表的第一個結點就是錯的,那麼判斷 樹的下一層結點(左右子樹也是或的關係),判斷左右子樹從頭開始對比鏈表。
  3. 遞歸的注意點:第一個條件應該是寫退出遞歸的條件,如果鏈表爲null,說明是true;如果數爲null,說明是false。
/**
 * 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) {
    // exit
        if (head == null) {
        return true;
        }
        if (root == null) {
        return false;
        }
        if (dfs(head, root)) {
        return true;
        }return isSubPath(head, root.left) || isSubPath(head, root.right);
    }public boolean dfs(ListNode head, TreeNode root) {
        // exit
        if (head == null) {
        return true;
        }
        if (root == null) {
        return false;
        }
        if (head.val != root.val) {
        return false;
        }return dfs(head.next, root.left) || dfs(head.next, root.right);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章