二叉树的垂直顺序遍历,使得节点被单独排序
给定一棵二叉树,垂直打印它。
注意:如果同一点有多个节点,则按排序顺序打印它们。
例子:
Input: 1
/ \
2 3
/ \ / \
4 11 6 7
/ \
8 9
Output: [ [4], [2], [1, 6, 11], [3, 8], [7], [9] ]
Explanation: Traversing the tree vertically gives the above output.
Input: 5
/ \
4 6
/ \ /
3 1 2
Output: [ [3], [4], [1, 2, 5], [6] ]
方法:这个问题类似于以垂直顺序打印二叉树。在那个问题中,如果有 2 个节点在同一垂直和同一水平上,则需要从左到右打印,但是这个问题需要按排序顺序打印。为此,采用由一对整数和多重集组成的队列和映射来存储多个节点,这些节点也可以具有相同的值。
下面是上述方法的实现。
C++
// C++ program for above approach
#include
using namespace std;
// Structure for a binary tree node
struct Node {
int key;
Node *left, *right;
};
// A utility function to create a new node
struct Node* newNode(int key)
{
struct Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return node;
}
// Function to print vertical traversal
// of a binary tree
vector > printVerticalOrder(Node* root)
{
// map > >
map > > mpp;
// queue
queue > > q;
q.push({ root, { 0, 0 } });
while (!q.empty()) {
auto p = q.front();
q.pop();
Node* temp = p.first;
// Vertical
int vertical = p.second.first;
// Level
int level = p.second.second;
// 2,0 -> {5,6} insert in the multiset
mpp[vertical][level].insert(temp->key);
// If left child of the node exits
// then push it on the queue
// with vertical decremented and
// level incremented
if (temp->left)
q.push({ temp->left,
{ vertical - 1,
level + 1 } });
// If right child of the node exits
// then push it on the queue
// with vertical incremented and
// level incremented
if (temp->right)
q.push({ temp->right,
{ vertical + 1,
level + 1 } });
}
vector > ans;
// Traverse the multiset part of each map
for (auto p : mpp) {
vector col;
for (auto q : p.second) {
col.insert(col.end(),
q.second.begin(),
q.second.end());
}
ans.push_back(col);
}
return ans;
}
// Driver Code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(11);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
root->right->right->right = newNode(9);
// To store the vertical order traversal
vector > v =
printVerticalOrder(root);
for (auto i : v) {
for (auto j : i) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
输出
4
2
1 6 11
3 8
7
9
时间复杂度: O(N*logN*logN*logN)
辅助空间: 在)