您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“C++怎么實(shí)現(xiàn)二叉樹(shù)層序遍歷”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“C++怎么實(shí)現(xiàn)二叉樹(shù)層序遍歷”吧!
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
層序遍歷二叉樹(shù)是典型的廣度優(yōu)先搜索 BFS 的應(yīng)用,但是這里稍微復(fù)雜一點(diǎn)的是,要把各個(gè)層的數(shù)分開(kāi),存到一個(gè)二維向量里面,大體思路還是基本相同的,建立一個(gè) queue,然后先把根節(jié)點(diǎn)放進(jìn)去,這時(shí)候找根節(jié)點(diǎn)的左右兩個(gè)子節(jié)點(diǎn),這時(shí)候去掉根節(jié)點(diǎn),此時(shí) queue 里的元素就是下一層的所有節(jié)點(diǎn),用一個(gè) for 循環(huán)遍歷它們,然后存到一個(gè)一維向量里,遍歷完之后再把這個(gè)一維向量存到二維向量里,以此類(lèi)推,可以完成層序遍歷,參見(jiàn)代碼如下:
解法一:
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { if (!root) return {}; vector<vector<int>> res; queue<TreeNode*> q{{root}}; while (!q.empty()) { vector<int> oneLevel; for (int i = q.size(); i > 0; --i) { TreeNode *t = q.front(); q.pop(); oneLevel.push_back(t->val); if (t->left) q.push(t->left); if (t->right) q.push(t->right); } res.push_back(oneLevel); } return res; } };
下面來(lái)看遞歸的寫(xiě)法,核心就在于需要一個(gè)二維數(shù)組,和一個(gè)變量 level,關(guān)于 level 的作用可以參見(jiàn)博主的另一篇博客 Binary Tree Level Order Traversal II 中的講解,參見(jiàn)代碼如下:
解法二:
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; levelorder(root, 0, res); return res; } void levelorder(TreeNode* node, int level, vector<vector<int>>& res) { if (!node) return; if (res.size() == level) res.push_back({}); res[level].push_back(node->val); if (node->left) levelorder(node->left, level + 1, res); if (node->right) levelorder(node->right, level + 1, res); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/102
類(lèi)似題目:
Binary Tree Level Order Traversal II
Binary Tree Zigzag Level Order Traversal
Minimum Depth of Binary Tree
Binary Tree Vertical Order Traversal
Average of Levels in Binary Tree
N-ary Tree Level Order Traversal
參考資料:
https://leetcode.com/problems/binary-tree-level-order-traversal/
https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33445/Java-Solution-using-DFS
https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33450/Java-solution-with-a-queue-used
https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/114449/A-general-approach-to-level-order-traversal-questions-in-Java
到此,相信大家對(duì)“C++怎么實(shí)現(xiàn)二叉樹(shù)層序遍歷”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。