Skip to content

Commit c6ba939

Browse files
committed
no message
1 parent 0e5f71d commit c6ba939

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
"""
2+
Time: O(N)
3+
Space: O(LogN) if the tree is balanced.
4+
5+
BFS is a more intuitive way to do this, but the time complexity will be at least O(N).
6+
Using recursion instead, will take O(LogN) for the recursion stack size.
7+
"""
8+
class Solution:
9+
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
10+
def helper(node, level):
11+
if not node: return
12+
if len(ans)<level: ans.append(node.val)
13+
helper(node.right, level+1)
14+
helper(node.left, level+1)
15+
16+
ans = []
17+
helper(root, 1)
18+
return ans
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
Time: O(N)
3+
Space: O(LogN) for recursion stack if the tree is balanced.
4+
"""
5+
class Solution:
6+
def goodNodes(self, root: TreeNode) -> int:
7+
def helper(node, maxVal):
8+
nonlocal count
9+
if not node: return
10+
if node.val>=maxVal: count += 1
11+
helper(node.left, max(maxVal, node.val))
12+
helper(node.right, max(maxVal, node.val))
13+
14+
count = 0
15+
helper(root, float('-inf'))
16+
return count
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
The inorder travsersal of a BST is always increasing.
3+
4+
Time: O(N)
5+
Space: O(N)
6+
"""
7+
class Solution:
8+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
9+
lastVal = float('-inf')
10+
stack = []
11+
12+
node = root
13+
while stack or node:
14+
while node:
15+
stack.append(node)
16+
node = node.left
17+
18+
node = stack.pop()
19+
20+
if not lastVal<node.val: return False
21+
lastVal = node.val
22+
23+
node = node.right
24+
return True

0 commit comments

Comments
 (0)