Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:

answer = dict()

for k, v in enumerate(nums):

if v in answer:
return [answer[v], k]
else:
answer[target - v] = k

return []
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
import re

class Solution:
def isPalindrome(self, s: str) -> bool:

# To lowercase
s = s.lower()

# Remove non-alphanumeric characters
s = re.sub(pattern=r'[^a-zA-Z0-9]', repl='', string=s)

# Determine if s is palindrome or not
len_s = len(s)

for i in range(len_s//2):

if s[i] != s[len_s - 1 - i]:
return False

return True
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return

current = root

while current:
if current.left:
# Find the rightmost node in the left subtree
rightmost = current.left
while rightmost.right:
rightmost = rightmost.right

# Save the current right subtree
# Connect it to the rightmost node of left subtree
rightmost.right = current.right

# Move the left subtree to the right
current.right = current.left
current.left = None

# Move to the next node
current = current.right
Original file line number Diff line number Diff line change
@@ -1,60 +1,46 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod
from collections import deque
class _Node {
val: number
left: _Node | null
right: _Node | null
next: _Node | null

class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
constructor(val?: number, left?: _Node, right?: _Node, next?: _Node) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
this.next = (next===undefined ? null : next)
}
}

class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None

# BFS using queue
queue = deque([root])
function connect(root: _Node | null): _Node | null {
if (!root) {
return null;
}

// BFS using queue
const queue: _Node[] = [root];

while (queue.length > 0) {
const levelSize = queue.length;

while queue:
level_size = len(queue)
// Process all nodes at current level
for (let i = 0; i < levelSize; i++) {
const node = queue.shift()!;

# Process all nodes at current level
for i in range(level_size):
node = queue.popleft()

# Connect to next node in the level (if not the last node)
if i < level_size - 1:
node.next = queue[0]

# Add children to queue for next level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)

return root


/**
* Definition for _Node.
* class _Node {
* val: number
* left: _Node | null
* right: _Node | null
* next: _Node | null
*
* constructor(val?: number, left?: _Node, right?: _Node, next?: _Node) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* this.next = (next===undefined ? null : next)
* }
* }
*/


function connect(root: _Node | null): _Node | null {
// Connect to next node in the level (if not the last node)
if (i < levelSize - 1) {
node.next = queue[0];
}

// Add children to queue for next level
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
}

};
return root;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { TreeNode } from './TreeNode';

function flatten(root: TreeNode | null): void {
if (!root) {
return;
}

let current: TreeNode | null = root;

while (current) {
if (current.left) {
// Find the rightmost node in the left subtree
let rightmost: TreeNode = current.left;
while (rightmost.right) {
rightmost = rightmost.right;
}

// Save the current right subtree
// Connect it to the rightmost node of left subtree
rightmost.right = current.right;

// Move the left subtree to the right
current.right = current.left;
current.left = null;
}

// Move to the next node
current = current.right;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import unittest
from typing import Optional, List
from src.my_project.interviews.top_150_questions_round_22\
.ex_72_flatten_binary_tree_to_linked_list import Solution, TreeNode


class FlattenBinaryTreeToLinkedListTestCase(unittest.TestCase):

def build_tree(self, values: List[Optional[int]]) -> Optional[TreeNode]:
"""Build tree from level-order list representation."""
if not values:
return None

root = TreeNode(values[0])
queue = [root]
i = 1

while queue and i < len(values):
node = queue.pop(0)

# Add left child
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1

# Add right child
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1

return root

def tree_to_array(self, root: Optional[TreeNode]) -> List[Optional[int]]:
"""Convert flattened tree to array format."""
result = []
current = root

while current:
result.append(current.val)
result.append(current.left) # Should always be None
current = current.right

return result

def test_example_1(self):
"""
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
"""
solution = Solution()
root = self.build_tree([1, 2, 5, 3, 4, None, 6])
solution.flatten(root)
output = self.tree_to_array(root)
expected = [1, None, 2, None, 3, None, 4, None, 5, None, 6, None]
self.assertEqual(output, expected)

def test_example_2(self):
"""
Input: root = []
Output: []
"""
solution = Solution()
root = self.build_tree([])
solution.flatten(root)
output = self.tree_to_array(root)
expected = []
self.assertEqual(output, expected)

def test_example_3(self):
"""
Input: root = [0]
Output: [0]
"""
solution = Solution()
root = self.build_tree([0])
solution.flatten(root)
output = self.tree_to_array(root)
expected = [0, None]
self.assertEqual(output, expected)