Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cb46cb8

Browse files
author
Amogh Singhal
authored
Create find_second_largest.py
1 parent bd36c9a commit cb46cb8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎find_second_largest.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
class Node:
3+
def __init__(self, data):
4+
self.data = data
5+
self.left = None
6+
self.right = None
7+
8+
def find_largest(root):
9+
current = root
10+
while current is not None:
11+
if current.right is not None:
12+
return current.right.data
13+
current = current.right
14+
15+
def find_second_largest(root):
16+
if root is None or (root.left is None and root.right is None):
17+
raise ValueError("Tree must atleast have 2 nodes")
18+
19+
current = root
20+
21+
while current is not None:
22+
if(current.left is not None and current.right is None):
23+
return find_largest(current.left)
24+
25+
if(current.right is not None and current.right.left is None and current.right.right is None):
26+
return current.data
27+
28+
current = current.right
29+
30+
node = Node(10)
31+
node.left = Node(5)
32+
node.left.left = Node(1)
33+
node.right = Node(50)
34+
node.right.left = Node(45)
35+
node.right.right = Node(100)
36+
37+
result = find_second_largest(node)
38+
print(result)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /