java: add «1367. Linked List in Binary Tree»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
548b824d4a
commit
2ee32d75a6
2 changed files with 52 additions and 0 deletions
15
java/ListNode.java
Normal file
15
java/ListNode.java
Normal file
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
37
java/linked-list-in-binary-tree.java
Normal file
37
java/linked-list-in-binary-tree.java
Normal file
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue