Trying to understand binary tree from array
This commit is contained in:
+65
-1
@@ -1,6 +1,11 @@
|
||||
import typing
|
||||
|
||||
|
||||
class LinkedListNode(typing.Protocol):
|
||||
val: int
|
||||
next: typing.Optional["LinkedListNode"]
|
||||
|
||||
|
||||
class ListNode:
|
||||
"""ListNode is the leetcode "standard library" type used in linked lists"""
|
||||
|
||||
@@ -9,8 +14,67 @@ class ListNode:
|
||||
self.next = next
|
||||
|
||||
|
||||
class BinaryTreeNode(typing.Protocol):
|
||||
val: int
|
||||
left: typing.Optional["BinaryTreeNode"]
|
||||
right: typing.Optional["BinaryTreeNode"]
|
||||
|
||||
|
||||
class TreeNode:
|
||||
"""TreeNode is the leetcode "standard library" type used in binary trees"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
val: int = 0,
|
||||
left: typing.Optional["TreeNode"] = None,
|
||||
right: typing.Optional["TreeNode"] = None,
|
||||
):
|
||||
self.val = val
|
||||
self.left = left
|
||||
self.right = right
|
||||
|
||||
@classmethod
|
||||
def from_int(cls, val: int | None) -> typing.Optional["TreeNode"]:
|
||||
if val is None:
|
||||
return None
|
||||
|
||||
return TreeNode(val)
|
||||
|
||||
# __repr__ was added by me
|
||||
def __repr__(self) -> str:
|
||||
filtered_parts = []
|
||||
|
||||
for key, value in [
|
||||
("val", self.val),
|
||||
("right", self.right),
|
||||
("left", self.left),
|
||||
]:
|
||||
if value is not None:
|
||||
filtered_parts.append((key, value))
|
||||
|
||||
middle = ", ".join([f"{k}={v!r}" for k, v in filtered_parts])
|
||||
|
||||
return f"TreeNode({middle})"
|
||||
|
||||
# __eq__ was added by me
|
||||
def __eq__(self, other: typing.Optional["TreeNode"]) -> bool:
|
||||
return (
|
||||
other is not None
|
||||
and self.val == other.val
|
||||
and self.left == other.left
|
||||
and self.right == other.right
|
||||
)
|
||||
|
||||
|
||||
class ConnectableBinaryTreeNode(typing.Protocol):
|
||||
val: int
|
||||
left: typing.Optional["BinaryTreeNode"]
|
||||
right: typing.Optional["BinaryTreeNode"]
|
||||
next: typing.Optional["BinaryTreeNode"]
|
||||
|
||||
|
||||
class Node:
|
||||
"""Node is the leetcode "standard library" type used in binary trees"""
|
||||
"""Node is the *other* leetcode "standard library" type used in binary trees"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
Reference in New Issue
Block a user