forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_second_largest_node.py
More file actions
53 lines (40 loc) · 1.24 KB
/
find_second_largest_node.py
File metadata and controls
53 lines (40 loc) · 1.24 KB
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
52
53
'''
Find second largest node (not search tree)
Given the root to a tree (not bst), find the second largest node in the tree.
=========================================
Traverse tree and compare the current value with the saved 2 values.
Time Complexity: O(N)
Space Complexity: O(N) , because of the recursion stack (but this is the tree is one branch), O(LogN) if the tree is balanced.
'''
############
# Solution #
############
# import TreeNode class from tree_helpers.py
from tree_helpers import TreeNode
import math
def find_second_largest(root):
arr = [TreeNode(-math.inf), TreeNode(-math.inf)]
traverse_tree(root, arr)
if arr[1] == -math.inf:
# the tree has 0 or 1 elements
return None
return arr[1]
def traverse_tree(node, arr):
if node == None:
return
if arr[0].val < node.val:
arr[1] = arr[0]
arr[0] = node
elif arr[1].val < node.val:
arr[1] = node
# search left
traverse_tree(node.left, arr)
# search right
traverse_tree(node.right, arr)
###########
# Testing #
###########
# Test 1
# Correct result => 8
tree = TreeNode(1, TreeNode(5, TreeNode(2), TreeNode(8)), TreeNode(4, TreeNode(12), TreeNode(7)))
print(find_second_largest(tree).val)