C++实现:
class Solution {
public:
map<int,vector<int> > m;// record idx
unordered_map<int,int> h; //record high
void preorder(int idx,TreeNode* root,int high){//前序遍历 记录位置 和层次
if(!root) return;
m[idx].push_back(root->val);
h[root->val] = high;//保证不存在重复值,对每一个节点有一个对应的高度
preorder(idx-1,root->left,high+1);
preorder(idx+1,root->right,high+1);
}
void mysort(vector<int> &a){//对每一列排序,高度不同则暗战高度排列,高度相同比较节点值大小
for(int i = 0;i<a.size();++i){
bool tag= false;
for(int j = a.size()-1;j>i;--j){
if(h[a[j-1]]>h[a[j]]){
swap(a[j-1],a[j]);
tag= true;
}
else if(h[a[j-1]]==h[a[j]]&&a[j-1]>a[j]){
swap(a[j-1],a[j]);
tag= true;
}
}
if(tag==false) break;//已排好则提前退出
}
}
vector<vector<int>> verticalTraversal(TreeNode* root) {
vector<vector<int>> ret;
if(!root) return ret;
preorder(0,root,0);
for(auto &it:m){
mysort(it.second);//取保存的第二项
ret.push_back(it.second);
}
return ret;
}
};
本文介绍了一种使用C++实现的二叉树垂直遍历算法,通过前序遍历记录每个节点的位置和层次,然后对每一列进行排序,确保同一水平线上的节点按高度和值的顺序排列。
936

被折叠的 条评论
为什么被折叠?



