当前位置:
首页 >
LeetCode 987. 二叉树的垂序遍历(递归/循环)
发布时间:2024/7/5
47
豆豆
生活随笔
收集整理的这篇文章主要介绍了
LeetCode 987. 二叉树的垂序遍历(递归/循环)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1. 题目
给定二叉树,按垂序遍历返回其结点值。
对位于 (X, Y) 的每个结点而言,其左右子结点分别位于 (X-1, Y-1) 和 (X+1, Y-1)。
把一条垂线从 X = -infinity 移动到 X = +infinity ,每当该垂线与结点接触时,我们按从上到下的顺序报告结点的值( Y 坐标递减)。
如果两个结点位置相同,则首先报告的结点值较小。
按 X 坐标顺序返回非空报告的列表。每个报告都有一个结点值列表。
示例 1:
示例 2:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/vertical-order-traversal-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- map的key记录x坐标,value记录点的集合{val, 深度}
- 对x一样的点集,按深度第一,值第二进行排序
2.1 递归
class Solution { map<int, vector<vector<int>>> m;//x坐标,节点集合< <val, deep> > public:vector<vector<int>> verticalTraversal(TreeNode* root) {//前序遍历 根左右if(!root)return {};dfs(root,0,0);vector<vector<int>> temp;vector<vector<int>> ans(m.size());int i = 0, j;for(auto it = m.begin(); it != m.end(); ++it){temp = it->second;//点集合sort(temp.begin(), temp.end(),[&](auto a, auto b){if(a[1] == b[1])return a[0] < b[0];//深度一样,按值return a[1] < b[1];//深度小的在前});for(j = 0; j < temp.size(); ++j)ans[i].push_back(temp[j][0]);//数值写入答案i++;}return ans;}void dfs(TreeNode* root, int x, int deep){if(!root)return;m[x].push_back({root->val,deep});dfs(root->left, x-1, deep+1);dfs(root->right, x+1, deep+1);} };24 ms 16.3 MB
2.2 层序遍历
class Solution { public:vector<vector<int>> verticalTraversal(TreeNode* root) {map<int, vector<vector<int>>> m;//x坐标,节点集合< <val, deep> >if(!root)return {};queue<pair<TreeNode*,pair<int,int>>> q;//节点及其坐标x,yq.push({root,{0,0}});pair<TreeNode*,pair<int,int>> tp;TreeNode* node;int x, y;while(!q.empty()){tp = q.front();q.pop();node = tp.first;x = tp.second.first;y = tp.second.second;m[x].push_back(vector<int> {node->val,y});if(node->left)q.push({node->left, {x-1,y+1}});if(node->right)q.push({node->right, {x+1,y+1}});}vector<vector<int>> temp;vector<vector<int>> ans(m.size());int i = 0, j;for(auto it = m.begin(); it != m.end(); ++it){temp = it->second;sort(temp.begin(), temp.end(),[&](auto a, auto b){if(a[1] == b[1])return a[0] < b[0];//深度一样,按值return a[1] < b[1];//深度小的在前});for(j = 0; j < temp.size(); ++j)ans[i].push_back(temp[j][0]);//数值写入答案i++;}return ans;} };16 ms 13.2 MB
创作挑战赛新人创作奖励来咯,坚持创作打卡瓜分现金大奖总结
以上是生活随笔为你收集整理的LeetCode 987. 二叉树的垂序遍历(递归/循环)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: LeetCode 971. 翻转二叉树以
- 下一篇: LeetCode 156. 上下翻转二叉