[leetcode] 107. Binary Tree Level Order Traversal II

网友投稿 246 2022-08-26

[leetcode] 107. Binary Tree Level Order Traversal II

Description

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example: Given binary tree [3,9,20,null,null,15,7],

3 / \ 9 20 / \ 15 7

return its bottom-up level order traversal as:

[ [15,7], [9,20], [3]]

分析

这道题目用了BFS,进行层序遍历,用队列来实现这一过程。然后用vector装结果,由于题目要求自底向上,我们是自顶向下求的,因此我们需要把顺序翻转一下。

代码

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector> levelOrderBottom(TreeNode* root) { vector> res; if(!root){ return res; } queue q; TreeNode* tmp; q.push(root); while(!q.empty()){ int t=q.size(); vector v; for(int i=0;ival); if(tmp->left){ q.push(tmp->left); } if(tmp->right){ q.push(tmp->right); } } res.push_back(v); } reverse(res.begin(),res.end()); return res; } };

参考文献

​​[编程题]binary-tree-level-order-traversal-ii​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 124. Binary Tree Maximum Path Sum
下一篇:为什么布局了100+社交媒体账号,却依然做不好社会化营销?(社交媒体覆盖率)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~