C++实现二叉树垂直顺序遍历
假设有一个二叉树,我们需要找到其节点值的垂直顺序遍历。如果两个节点在同一行和同一列,则顺序应从左到右。
因此,如果输入如下所示:

则输出将为 [[9],[3,15],[20],[7]]
为了解决这个问题,我们将遵循以下步骤:
定义一个map m
定义一个函数solve(),它将接收节点node,并初始化x为0,
如果node为空,则:
返回
solve(node的左子节点, x - 1)
solve(node的右子节点, x + 1)
将node的值插入到m[x]的末尾
在主方法中,执行以下操作:
如果root为空,则:
返回{}
定义一个队列q
将{0, root}插入到q中
将node的值插入到m[0]的末尾
当(q不为空)时,执行:
sz := q的大小
当sz不为零时,每次迭代减少sz,执行:
curr := q的第一个元素
从q中删除元素
node = curr的第二个元素
x := curr的第一个元素
如果node的左子节点不为空,则:
将{x - 1, node的左子节点}插入到q中
将node的左子节点的值插入到m[x - 1]的末尾
如果node的右子节点不为空,则:
将{x + 1, node的右子节点}插入到q中
将node的右子节点的值插入到m[x + 1]的末尾
定义一个二维数组ret
对于m的每个键值对'it':
将it的值插入到ret中
返回ret
示例
让我们看一下下面的实现,以便更好地理解:
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto< > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int< v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
class Solution {
public:
map<int, vector<int< > m;
void solve(TreeNode* node, int x = 0){
if (!node || node->val == 0)
return;
solve(node->left, x - 1);
solve(node->right, x + 1);
m[x].push_back(node->val);
}
static bool cmp(vector<int<& a, vector<int<& b){
return a[0] != b[0] ? a[0] < b[0] : a[1] < b[1];
}
vector<vector<int< > verticalOrder(TreeNode* root){
if (!root)
return {};
queue<pair > q;
q.push({ 0, root });
m[0].push_back(root->val);
while (!q.empty()) {
int sz = q.size();
while (sz--) {
pair<int, TreeNode*> curr = q.front();
q.pop();
TreeNode* node = curr.second;
int x = curr.first;
if (node->left && node->left->val != 0) {
q.push({ x - 1, node->left });
m[x - 1].push_back(node->left->val);
}
if (node->right && node->right->val != 0) {
q.push({ x + 1, node->right });
m[x + 1].push_back(node->right->val);
}
}
}
vector<vector<int< > ret;
map<int, vector<int< >::iterator it = m.begin();
while (it != m.end()) {
ret.push_back(it->second);
it++;
}
return ret;
}
};
main(){
Solution ob;
vector<int< v = {3,9,20,NULL,NULL,15,7};
TreeNode *root = make_tree(v);
print_vector(ob.verticalOrder(root));
}输入
{3,9,20,NULL,NULL,15,7}输出
[[9, ],[3, 15, ],[20, ],[7, ],]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP