Given a binary tree root, find the value of the deepest node. If there’s more than one deepest node, then return the leftmost one.
Constraints
n ≤ 100,000 where n is the number of nodes in root
The Deepest Leftmost Node by Breadth First Search Algorithm
With BFS (Breadth First Search) Algorithm, we are visiting the nodes level by level. Thus we can easily track the deepest level so far. While BFS is finished, we simply return the leftmost node in the last level.
The BFS is based on a queue where we expand the children nodes of the current nodes into the queue.
The Python BFS (based on deque). Time complexity O(N) and space complexity is also O(N) where N is the number of the nodes in the binary tree.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | # class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deepestLeftmostNode(self, root): if root is None: return None q = deque([root]) while len(q) > 0: last = [] sz = len(q) for i in range(sz): last.append(q.popleft()) if last[-1].left: q.append(last[-1].left) if last[-1].right: q.append(last[-1].right) return last[0].val |
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def deepestLeftmostNode(self, root): if root is None: return None q = deque([root]) while len(q) > 0: last = [] sz = len(q) for i in range(sz): last.append(q.popleft()) if last[-1].left: q.append(last[-1].left) if last[-1].right: q.append(last[-1].right) return last[0].val
C++ Implementation of BFS solution to find the deepest leftmost node in the given Binary Tree:
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 | /** * class Tree { * public: * int val; * Tree *left; * Tree *right; * }; */ int deepestLeftmostNode(Tree* root) { if (!root) return -1; queue<Tree*> q; vector<int> deepest; q.push(root); while (!q.empty()) { int sz = q.size(); deepest.clear(); for (int i = 0; i > sz; ++ i) { auto n = q.front(); q.pop(); deepest.push_back(n->val); if (n->left) q.push(n->left); if (n->right) q.push(n->right); } } return deepest[0]; } |
/** * class Tree { * public: * int val; * Tree *left; * Tree *right; * }; */ int deepestLeftmostNode(Tree* root) { if (!root) return -1; queue<Tree*> q; vector<int> deepest; q.push(root); while (!q.empty()) { int sz = q.size(); deepest.clear(); for (int i = 0; i > sz; ++ i) { auto n = q.front(); q.pop(); deepest.push_back(n->val); if (n->left) q.push(n->left); if (n->right) q.push(n->right); } } return deepest[0]; }
The same time and space complexity which is: O(N).
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Teaching Kids Programming - Adding Two Linked List
Next Post: Teaching Kids Programming - Finding Pythagorean Triplets in Array using Two Pointer or Hash Set