From 2ee32d75a6ed2afc25a80f82e4a32ea7372ed8ca Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 7 Sep 2024 12:29:14 +0200 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB1367.=20Linked=20List=20in?= =?UTF-8?q?=20Binary=20Tree=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/ListNode.java | 15 +++++++++++ java/linked-list-in-binary-tree.java | 37 ++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 java/ListNode.java create mode 100644 java/linked-list-in-binary-tree.java diff --git a/java/ListNode.java b/java/ListNode.java new file mode 100644 index 0000000..179e94e --- /dev/null +++ b/java/ListNode.java @@ -0,0 +1,15 @@ +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; + } +} diff --git a/java/linked-list-in-binary-tree.java b/java/linked-list-in-binary-tree.java new file mode 100644 index 0000000..4f819db --- /dev/null +++ b/java/linked-list-in-binary-tree.java @@ -0,0 +1,37 @@ +class Solution { + private boolean matches(ListNode head, TreeNode node) { + // linked list ran out ⇒ matches + if (head == null) { + return true; + } + + // ran out of tree nodes ⇒ failed + if (node == null) { + return false; + } + + // values don't match ⇒ failed + if (head.val != node.val) { + return false; + } + + // check rest of the path + return matches(head.next, node.left) || matches(head.next, node.right); + } + + public boolean isSubPath(ListNode head, TreeNode node) { + // cannot form a subpath + if (node == null) { + return false; + } + + // check path starting from the current node + var result = matches(head, node); + + // if doesn't match linked list, try from subtrees + result = result || isSubPath(head, node.left); + result = result || isSubPath(head, node.right); + + return result; + } +}