C++實(shí)現(xiàn)LeetCode(199.二叉樹的右側(cè)視圖)
[LeetCode] 199.Binary Tree Right Side View 二叉樹的右側(cè)視圖
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
這道題要求我們打印出二叉樹每一行最右邊的一個數(shù)字,實(shí)際上是求二叉樹層序遍歷的一種變形,我們只需要保存每一層最右邊的數(shù)字即可,可以參考我之前的博客 Binary Tree Level Order Traversal 二叉樹層序遍歷,這道題只要在之前那道題上稍加修改即可得到結(jié)果,還是需要用到數(shù)據(jù)結(jié)構(gòu)隊列queue,遍歷每層的節(jié)點(diǎn)時,把下一層的節(jié)點(diǎn)都存入到queue中,每當(dāng)開始新一層節(jié)點(diǎn)的遍歷之前,先把新一層最后一個節(jié)點(diǎn)值存到結(jié)果中,代碼如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode *root) { vector<int> res; if (!root) return res; queue<TreeNode*> q; q.push(root); while (!q.empty()) { res.push_back(q.back()->val); int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return res; } };
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(199.二叉樹的右側(cè)視圖)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)二叉樹的右側(cè)視圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++ 中dynamic_cast<>的使用方法小結(jié)
將一個基類對象指針(或引用)cast到繼承類指針,dynamic_cast會根據(jù)基類指針是否真正指向繼承類指針來做相應(yīng)處理2013-03-03C語言使用單鏈表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言使用單鏈表實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11詳解如何在C/C++中測量一個函數(shù)或功能的運(yùn)行時間
本文算是一個比較完整的關(guān)于在 C/C++ 中測量一個函數(shù)或者功能的總結(jié),最后會演示三種方法的對比,文章通過代碼示例給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12