less than 1 minute read

Given a binary tree root, return the leftmost node’s value on each level of the tree.

Constraints

  • n ≤ 100,000 where n is the number of nodes in root

https://binarysearch.com/problems/Left-Side-View-of-a-Tree

ExamplesPermalink

Example 1Permalink

Input

  • root =
example1Root 0 0 1 5 0->1 2 2 0->2 3 1 2->3

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