Left Side View of a Tree
Given a binary tree root
, return the leftmost node’s value on each level of the tree.
Constraints
n ≤ 100,000
wheren
is the number of nodes inroot
https://binarysearch.com/problems/Left-Side-View-of-a-Tree
ExamplesPermalink
Example 1Permalink
Input
- root =
Output
- answer =
[0, 5, 1]
SolutionPermalink
/** | |
* class Tree { | |
* public: | |
* int val; | |
* Tree *left; | |
* Tree *right; | |
* }; | |
*/ | |
vector<int> solve(Tree *root) | |
{ | |
vector<int> res; | |
if (!root) | |
return res; | |
queue<Tree *> q; | |
q.push(root); | |
while (!q.empty()) | |
{ | |
int levelSize = q.size(); | |
res.push_back(q.front()->val); | |
while (levelSize--) | |
{ | |
Tree *node = q.front(); | |
q.pop(); | |
if (node->left) | |
q.push(node->left); | |
if (node->right) | |
q.push(node->right); | |
} | |
} | |
return res; | |
} |
Leave a comment