Przeglądaj źródła

Did the pre-order traversal problem

master
Lachlan Jacob 5 lat temu
rodzic
commit
84cd0e5f28
3 zmienionych plików z 47 dodań i 0 usunięć
  1. 31
    0
      1008/main.py
  2. 13
    0
      1008/problem.txt
  3. 3
    0
      1008/run.sh

+ 31
- 0
1008/main.py Wyświetl plik

@@ -0,0 +1,31 @@
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

def __str__(self):
return "\nValue: " + str(self.val) + "\nLeft:" + str(self.left) + "\nRight:" + str(self.right)

class Solution:
def bstFromPreorder(self, preorder):
if preorder is None or len(preorder) == 0:
return None
elif len(preorder) == 1:
return TreeNode(preorder[0])
root = TreeNode(preorder[0])
# now collect the nodes that are less than root and make a tree from them
leftChildrenItems = list(filter(lambda x: x < preorder[0], preorder[1:]))
rightChildrenItems = list(filter(lambda x: x > preorder[0], preorder[1:])) # don't need >= because items are distinct
root.left = self.bstFromPreorder(leftChildrenItems)
root.right = self.bstFromPreorder(rightChildrenItems)
return root

s = Solution()
print("Expected: [4, 2]")
print("Got:", s.bstFromPreorder([4, 2]))

+ 13
- 0
1008/problem.txt Wyświetl plik

@@ -0,0 +1,13 @@
Return the root node of a binary search tree that matches the given preorder traversal.

(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Note:

1 <= preorder.length <= 100
The values of preorder are distinct.

+ 3
- 0
1008/run.sh Wyświetl plik

@@ -0,0 +1,3 @@
#!/bin/bash

python3 main.py

Ładowanie…
Anuluj
Zapisz