-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbt_ll_traversal_examples.py
51 lines (48 loc) · 1.61 KB
/
bt_ll_traversal_examples.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#Binary Tree traversal with Queue (Breadth-first search / In Order)
from collections import deque
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
queue = deque([root])
sumz = 0
while queue:
node = queue.popleft()
if node.val <= R and node.val >= L:
sumz += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return sumz
#Binary Tree traversal through recursion (Depth-first search)
class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
def traverseBST(root,L,R):
if not root:
return
if root.val >= L and root.val <= R:
self.sumz += root.val
traverseBST(root.left,L,R)
traverseBST(root.right,L,R)
self.sumz = 0
traverseBST(root,L,R)
return self.sumz
#Linked List traversal (iteratively)
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
result = []
while head:
result.append(head)
head = head.next
return result[(len(result)//2)]
#Linked List traversal (recursively)
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
self.result = []
def traverse(head):
if not head:
return
self.result.append(head)
traverse(head.next)
traverse(head)
return self.result[(len(self.result)//2)]
# remember to use self. if it needs to be global