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