https://leetcode.com/problems/binary-tree-right-side-view/description/
주어진 tree의 각 level의 마지막 값을 구하라.
level order traversal을 한 후 제일 마지막 값만을 취한다.
코드
더보기
vector<int> rightSideView(TreeNode* root)
{
vector<int> vRet;
if (root == nullptr)
return vRet;
queue<TreeNode*> qBuff;
qBuff.push(root);
while (qBuff.size() > 0)
{
int cnt = qBuff.size();
for (int q = 0; q < cnt; ++q)
{
TreeNode* node = qBuff.front();
qBuff.pop();
if (q == cnt - 1)
vRet.push_back(node->val);
if (node->left != nullptr) qBuff.push(node->left);
if (node->right != nullptr) qBuff.push(node->right);
}
}
return vRet;
}
결과
'Leetcode > NeetCode' 카테고리의 다른 글
[👍][BinaryTree][Medium] 98. Validate Binary Search Tree (0) | 2024.07.18 |
---|---|
[BinaryTree][Medium] 1448. Count Good Nodes in Binary Tree (0) | 2024.07.18 |
[BinaryTree][Medium] 102. Binary Tree Level Order Traversal (0) | 2024.07.18 |
[BinaryTree][Medium] 235. Lowest Common Ancestor of a Binary Search Tree (0) | 2024.07.17 |
[BinaryTree][Easy] 572. Subtree of Another Tree (0) | 2024.07.17 |