GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — coding-problems/Trees/find_second_largest_node.py at master · ishan-pat/coding-problems

Expand file tree

/

find_second_largest_node.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
53 lines (40 loc) · 1.24 KB
/

find_second_largest_node.py

Copy path

File metadata and controls

53 lines (40 loc) · 1.24 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.