// print binary tree vertiacally.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
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;
}
void printTreeVertiacally(std::map<int, std::vector<Node *>> &nodeMap)
{
std::map<int, std::vector<Node*>>::iterator it = nodeMap.begin();
while(it != nodeMap.end())
{
for (int i=0; i<it->second.size(); ++i)
{
cout << it->second[i]->key << " ";
}
cout << endl;
++it;
}
}
void travelTree(Node *pNode, int curDistance, std::map<int, std::vector<Node*>> &nodeMap)
{
if (pNode == NULL)
return;
nodeMap[curDistance].push_back(pNode);
travelTree(pNode->left, curDistance-1, nodeMap);
travelTree(pNode->right, curDistance+1, nodeMap);
}
void printVerticalOrder(Node *root)
{
std::map<int, std::vector<Node*>> nodeMap;
travelTree(root, 0, nodeMap);
printTreeVertiacally(nodeMap);
}
int _tmain(int argc, _TCHAR* argv[])
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
root->right->right->right = newNode(9);
cout << "Vertical order traversal is \n";
printVerticalOrder(root);
return 0;
}
print binary tree vertically
最新推荐文章于 2021-02-27 03:47:25 发布