Skip to content

Commit 5111543

Browse files
committed
no message
1 parent 9f00706 commit 5111543

File tree

4 files changed

+98
-0
lines changed

4 files changed

+98
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Time: O(LogN)
3+
Space: O(1)
4+
5+
Basically we are going to search the target in the BST.
6+
Along the way, we compare it with the `ans`, if the difference is smaller, update it.
7+
"""
8+
class Solution(object):
9+
def closestValue(self, root, target):
10+
node = root
11+
ans = float('inf')
12+
13+
while node:
14+
if not node: break
15+
16+
if abs(ans-target)>abs(node.val-target):
17+
ans = node.val
18+
19+
if target>node.val:
20+
node = node.right
21+
else:
22+
node = node.left
23+
24+
return ans

problems/count-complete-tree-nodes.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
Time: O(H^2). The time complexity will countNodes() will be LogH if the tree is perfect.
3+
If not, we will need Log(H-1)
4+
5+
Space: O(H)
6+
"""
7+
class Solution(object):
8+
def countNodes(self, root):
9+
if not root: return 0
10+
11+
node = root
12+
l = 1 #level on the right side
13+
while node.left:
14+
node = node.left
15+
l += 1
16+
17+
node = root
18+
r = 1 #level on the left side
19+
while node.right:
20+
node = node.right
21+
r += 1
22+
23+
if l==r:
24+
#perfect tree
25+
return (2**r)-1
26+
else:
27+
return 1+self.countNodes(root.left)+self.countNodes(root.right)

problems/sum-root-to-leaf-numbers.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,30 @@ def sumNumbers(self, root):
4343
"""
4444

4545

46+
"""
47+
Time: O(N)
48+
Space: O(H)
49+
50+
Use standard DFS to traverse the tree.
51+
"""
52+
class Solution(object):
53+
def sumNumbers(self, root):
54+
ans = 0
55+
stack = [(root, '')]
56+
57+
while stack:
58+
node, numString = stack.pop()
59+
60+
if node.left:
61+
stack.append((node.left, numString+str(node.val)))
62+
if node.right:
63+
stack.append((node.right, numString+str(node.val)))
64+
65+
if not node.left and not node.right:
66+
ans += int(numString+str(node.val))
67+
return ans
68+
69+
4670

4771

4872

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution(object):
2+
def generateTrees(self, N):
3+
4+
#generateTrees from s to e
5+
def helper(s, e):
6+
trees = []
7+
8+
for i in xrange(s, e+1):
9+
leftTrees = helper(s, i-1)
10+
rightTrees = helper(i+1, e)
11+
12+
for leftTree in leftTrees:
13+
for rightTree in rightTrees:
14+
15+
root = TreeNode(i)
16+
root.left = leftTree
17+
root.right = rightTree
18+
trees.append(root)
19+
20+
return trees if trees else [None]
21+
22+
#remove None in the output
23+
return [tree for tree in helper(1, N) if tree]

0 commit comments

Comments
 (0)