forked from youngyangyang04/leetcode-master
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d5a824d
commit 7747476
Showing
5 changed files
with
137 additions
and
60 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
## 题目地址 | ||
https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/ | ||
|
||
## 思路 | ||
|
||
这道题目相对于[0102.二叉树的层序遍历](https://github.com/youngyangyang04/leetcode/blob/master/problems/0102.二叉树的层序遍历.md),就把结果倒叙过来,就可以了。 | ||
|
||
层序遍历一个二叉树。就是从左到右一层一层的去遍历二叉树。这种遍历的方式和我们之前讲过的都不太一样。 | ||
|
||
需要借用一个辅助数据结构队列来实现,**队列先进先出,符合一层一层遍历的逻辑,而是用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。** | ||
|
||
使用队列实现广度优先遍历,动画如下: | ||
|
||
<video src='../video/102二叉树的层序遍历.mp4' controls='controls' width='640' height='320' autoplay='autoplay'> Your browser does not support the video tag.</video></div> | ||
|
||
这样就实现了层序从左到右遍历二叉树。 | ||
|
||
代码如下:这份代码也可以作为二叉树层序遍历的模板。 | ||
|
||
## C++代码 | ||
|
||
``` | ||
class Solution { | ||
public: | ||
vector<vector<int>> levelOrderBottom(TreeNode* root) { | ||
queue<TreeNode*> que; | ||
if (root != NULL) que.push(root); | ||
vector<vector<int>> result; | ||
while (!que.empty()) { | ||
int size = que.size(); | ||
vector<int> vec; | ||
for (int i = 0; i < size; i++) {// 这里一定要使用固定大小size,不要使用que.size() | ||
TreeNode* node = que.front(); | ||
que.pop(); | ||
vec.push_back(node->val); | ||
if (node->left) que.push(node->left); | ||
if (node->right) que.push(node->right); | ||
} | ||
result.push_back(vec); | ||
} | ||
reverse(result.begin(), result.end()); | ||
return result; | ||
} | ||
}; | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.