您好,登錄后才能下訂單哦!
本篇內容主要講解“C++怎么實現二叉樹層序遍歷”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++怎么實現二叉樹層序遍歷”吧!
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]
]
層序遍歷二叉樹是典型的廣度優先搜索 BFS 的應用,但是這里稍微復雜一點的是,要把各個層的數分開,存到一個二維向量里面,大體思路還是基本相同的,建立一個 queue,然后先把根節點放進去,這時候找根節點的左右兩個子節點,這時候去掉根節點,此時 queue 里的元素就是下一層的所有節點,用一個 for 循環遍歷它們,然后存到一個一維向量里,遍歷完之后再把這個一維向量存到二維向量里,以此類推,可以完成層序遍歷,參見代碼如下:
解法一:
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; } };
下面來看遞歸的寫法,核心就在于需要一個二維數組,和一個變量 level,關于 level 的作用可以參見博主的另一篇博客 Binary Tree Level Order Traversal II 中的講解,參見代碼如下:
解法二:
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
類似題目:
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
到此,相信大家對“C++怎么實現二叉樹層序遍歷”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。