[Algorithm] Leftmost Deepest Tree Node (Tree/C++)

Changjin
1 min readJan 16, 2021

Problem Link: https://binarysearch.com/room/Graph-Traversers-gi4poVe0pC

This problem is to find the value of the deepest value. If there are multiple such values, return the leftmost one. We can approach this question in two different ways(there’re other ways too): DFS and BFS.

DFS

First, set the initial pair<int,int>p such that p.first=level, p.second=value. As we go down to the deeper level, we keep tracking of the level. When the current level is greater than the p.first, then update the value. As we call dfs(root->left) before dfs(root->right), this would give us the leftmost node at the deepest level.

BFS

The BFS approach is very straightforward. At each level, update the initial value(int res) as the first node at that level.

Both DFS/BFS take O(n) time since we traverse each and every node only once.

[Contact]
Email: changjin9792@gmail.com
Github: https://github.com/JasonLee-cp
️✅ Medium: https://changjin9792.medium.com/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Changjin
Changjin

No responses yet

Write a response