def enQueue(self, value: int) -> bool: if self.isFull(): return False if self.isEmpty(): self.head = Node(value) self.tail = self.head else: newNode = Node(value) self.tail.next = newNode self.tail = newNode self.size += 1 return True
def cloneGraph(self, node: 'Node') -> 'Node': if node is None: return None cloned_node = Node(node.val) cloned_dict, queue = {node: cloned_node}, [node] while queue: current = queue.pop() for neighbor in current.neighbors: if neighbor not in cloned_dict: queue.append(neighbor) cloned_neighbor = Node(neighbor.val) cloned_dict[neighbor] = cloned_neighbor cloned_dict[current].neighbors.append(cloned_dict[neighbor]) return cloned_dict[node]
def copyRandomList(self, head: 'Node') -> 'Node': dummy = Node(-1) current, prev, copies = head, dummy, {} while current: copied = Node(current.val) copies[current] = copied prev.next = copied prev, current = prev.next, current.next current = head while current: if current.random: copies[current].random = copies[current.random] current = current.next return dummy.next
def flatten(self, head): if not head: return pseudoHead = Node(0, None, head, None) prev = pseudoHead stack = [] stack.append(head) while stack: curr = stack.pop() prev.next = curr curr.prev = prev if curr.next: stack.append(curr.next) if curr.child: stack.append(curr.child) # don't forget to remove all child pointers. curr.child = None prev = curr # detach the pseudo head node from the result. pseudoHead.next.prev = None return pseudoHead.next
def dfs(self, head, node_list): if not head or head.val is None: return node_list.append(Node(head.val)) if head.child: cld = head.child head.child = None self.dfs(cld, node_list) self.dfs(head.next, node_list)
def test_solution(): samples = [[[7, None], [13, 0], [11, 4], [10, 2], [1, 0]], [[1, 1], [2, 1]], [[3, None], [3, 0], [3, None]], []] lists = [Node.initList(x) for x in samples] # res = [sol.copyRandomList(x) for x in lists] res = [Solution().copyRandomList(x) for x in lists] res1 = [Solution1().copyRandomList(x) for x in lists] assert repr(lists) == repr(res) assert repr(lists) == repr(res1)
def flatten(self, head): if not head: return head # pseudo head to ensure the `prev` pointer is never none pseudoHead = Node(None, None, head, None) self.flatten_dfs(pseudoHead, head) # detach the pseudo head from the real head pseudoHead.next.prev = None return pseudoHead.next
def copyRandomList(self, head: 'Node') -> 'Node': if not head: return head clone = defaultdict(lambda: Node(0)) clone[None] = None cur = head while cur: clone[cur].val = cur.val clone[cur].next = clone[cur.next] clone[cur].random = clone[cur.random] cur = cur.next return clone[head]
def solve(self, data): num = 0 while data[self.pos].isdigit(): num *= 10 num += ord(data[self.pos]) - ord('0') self.pos += 1 node = Node(num, []) while self.pos < len(data): if data[self.pos] == '[': self.pos += 1 node.children.append(self.solve(data)) elif data[self.pos] == ']': self.pos += 1 return node
def test_solution(): root = Node( val=1, children=[Node(3, children=[Node(5), Node(6)]), Node(2), Node(4)]) coder = Codec() ss = coder.encode(root) # print(ss) assert repr(coder.decode(ss)) == repr(root)
def decode(self, data): """Decodes your binary tree to an n-ary tree. :type data: TreeNode :rtype: Node """ if not data: return None rootNode = Node(data.val, []) curr = data.left while curr: rootNode.children.append(self.decode(curr)) curr = curr.right return rootNode
def connect(self, root: 'Node') -> 'Node': """ Good https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-28/ """ if not root: return root cur = root while cur: dummy = Node(-1) tail = dummy # //遍历 cur 的当前层 while cur: if cur.left: tail.next = cur.left tail = tail.next if cur.right: tail.next = cur.right tail = tail.next cur = cur.next cur = dummy.next # //更新 cur 到下一层 return root
""" def cloneGraph(self, node: 'Node') -> 'Node': if node is None: return None cloned_node = Node(node.val) cloned_dict, queue = {node: cloned_node}, [node] while queue: current = queue.pop() for neighbor in current.neighbors: if neighbor not in cloned_dict: queue.append(neighbor) cloned_neighbor = Node(neighbor.val) cloned_dict[neighbor] = cloned_neighbor cloned_dict[current].neighbors.append(cloned_dict[neighbor]) return cloned_dict[node] # leetcode submit region end(Prohibit modification and deletion) @pytest.mark.parametrize("args,expected", [(Node(val=12, neighbors=[Node(3), Node(4)]), Node(val=12, neighbors=[Node(3), Node(4)]))]) def test_solutions(args, expected): res = Solution().cloneGraph(args) assert repr(res) == repr(expected) if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
return root class Solution2: def connect(self, root: 'Node') -> 'Node': """ Good """ if not root: return root if root.left: root.left.next = root.right if root.right and root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) return root @pytest.mark.parametrize("args,expected", [[ Node(1, Node(2, Node(4), Node(5), None), Node(3, Node(6), Node(7), None), None), [1, 2, 3, 4, 5, 6, 7] ]]) def test_solutions(args, expected): assert repr(Solution().connect(copy.deepcopy(args))) == repr(expected) assert repr(Solution1().connect(copy.deepcopy(args))) == repr(expected) assert repr(Solution2().connect(copy.deepcopy(args))) == repr(expected) if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
def test_solution(): p = Node(3, children=[Node(6)]) q = Node(8) root = Node(1, children=[ Node(2, children=[Node(4, children=[Node(7), q]), Node(5)]), p ]) expected = Node( 1, children=[ Node(2, children=[ Node(4, children=[ Node(7), Node(8, children=[Node(3, children=[Node(6)])]) ]), Node(5) ]) ]) res = Solution().moveSubTree(root, p, q) assert repr(expected) == repr(res)
def helper(): root = Node(int(next(data)), []) num = int(next(data)) for _ in range(num): root.children.append(helper()) return root
class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: if not root: return [] results = [] q = deque([root]) level = 0 while q: results.append([]) length = len(q) for i in range(length): node = q.popleft() results[level].append(node.val) if node.children: q.extend(node.children) level += 1 return results @pytest.mark.parametrize("kw,expected", [ [ dict(root=Node(1, [Node(3, [Node(5), Node( 6)]), Node(2), Node(4)])), [[1], [3, 2, 4], [5, 6]] ], ]) def test_solutions(kw, expected): assert Solution().levelOrder(**kw) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
# # # 树的深度不会超过 1000。 # 树的节点总不会超过 5000。 # Related Topics 树 深度优先搜索 广度优先搜索 # 👍 98 👎 0 import pytest from common_utils import TreeNodeWithChildren as Node class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 if not root.children: return 1 return max([self.maxDepth(node) for node in root.children]) + 1 @pytest.mark.parametrize("kw,expected", [ [dict(root=Node(1, [Node(3, [Node(5), Node(6)]), Node(2), Node(4)])), 3], ]) def test_solutions(kw, expected): assert Solution().maxDepth(**kw) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
class Solution: def preorder(self, root: 'Node') -> List[int]: if not root: return [] results = [] stack = [root] while stack: cur = stack.pop() results.append(cur.val) children = cur.children if children: for child in children[::-1]: stack.append(child) return results @pytest.mark.parametrize("kw,expected", [ [ dict(root=Node(1, [Node(3, [Node(5), Node( 6)]), Node(2), Node(4)])), [1, 3, 5, 6, 2, 4] ], ]) def test_solutions(kw, expected): assert Solution().preorder(**kw) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
current, prev, copies = head, dummy, {} while current: copied = Node(current.val) copies[current] = copied prev.next = copied prev, current = prev.next, current.next current = head while current: if current.random: copies[current].random = copies[current.random] current = current.next return dummy.next @pytest.mark.parametrize("args,expected", [[ Node.initList([[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]), Node.initList([[7, None], [13, 0], [11, 4], [10, 2], [1, 0]]), ]]) def test_solutions(args, expected): res = Solution().copyRandomList(args) cur_res = res cur_expected = expected while cur_res and cur_expected: assert cur_res.val == cur_expected.val if cur_res.random: assert cur_res.random.val == cur_expected.random.val cur_res, cur_expected = cur_res.next, cur_expected.next assert cur_res is None and cur_expected is None if __name__ == '__main__':
class Solution: def postorder(self, root: 'Node') -> List[int]: if not root: return [] results = [] stack = [(root, False)] while stack: cur, is_visited = stack.pop() if is_visited: results.append(cur.val) else: stack.append((cur, True)) if cur.children: for child in cur.children[::-1]: stack.append((child, False)) return results @pytest.mark.parametrize("args,expected", [[ Node(1, [Node(3, [Node(5), Node(6)]), Node(2), Node(4)]), [5, 6, 3, 2, 4, 1] ], [None, []], [Node(1), [1]]]) def test_solutions(args, expected): assert Solution().postorder(args) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])
def dfs(node): max_dia = max_depth = 0 for child in node.children: child_max_dia, child_max_depth = dfs(child) max_dia = max(max_dia, child_max_dia, max_depth + child_max_depth + 1) max_depth = max(max_depth, child_max_depth + 1) return max_dia, max_depth return dfs(root)[0] # leetcode submit region end(Prohibit modification and deletion) @pytest.mark.parametrize("kwargs,expected", [ [ dict(root=Node( 1, children=[Node(3, children=[Node(5), Node(6)]), Node(2), Node(4)])), 3 ], ]) def test_solutions(kwargs, expected): assert Solution().diameter(**kwargs) == expected if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=tee-sys", __file__])
class Solution1: def connect(self, root: 'Node') -> 'Node': if not root: return root queue = [root] while queue: size = len(queue) for i in range(size - 1): queue[i].next = queue[i + 1] for i in range(size): node = queue.pop(0) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root @pytest.mark.parametrize("args,expected", [ (Node(1, Node(2, None, Node(5), None), Node(3, None, Node(7), None), None), [1, 2, 3, '#', 5, '#', 7]) ]) @pytest.mark.parametrize("SolutionCLS", [Solution, Solution1]) def test_solutions(args, expected, SolutionCLS): assert repr(SolutionCLS().connect(args)) == repr(expected) if __name__ == '__main__': pytest.main(["-q", "--color=yes", "--capture=no", __file__])