about summary refs log tree commit diff
path: root/users/wpcarro/scratch/facebook/second-largest-item-in-bst.py
diff options
context:
space:
mode:
Diffstat (limited to 'users/wpcarro/scratch/facebook/second-largest-item-in-bst.py')
-rw-r--r--users/wpcarro/scratch/facebook/second-largest-item-in-bst.py22
1 files changed, 22 insertions, 0 deletions
diff --git a/users/wpcarro/scratch/facebook/second-largest-item-in-bst.py b/users/wpcarro/scratch/facebook/second-largest-item-in-bst.py
new file mode 100644
index 000000000000..2815dec9ee60
--- /dev/null
+++ b/users/wpcarro/scratch/facebook/second-largest-item-in-bst.py
@@ -0,0 +1,22 @@
+from collections import deque
+from node import Node, tree
+
+def find_largest(node):
+    while node.right:
+        node = node.right
+    return node.value
+
+def find_second_largest(node):
+    # parent of the rightmost, when rightmost is leaf
+    # max(rightmost.left)
+    prev = None
+    while node.right:
+        prev = node
+        node = node.right
+    if node.left:
+        return find_largest(node.left)
+    else:
+        return prev.value
+
+assert find_second_largest(tree) == 72
+print("Success!")