二叉树的垂直遍历

来源:互联网 发布:数据库分为哪几种类型 编辑:程序博客网 时间:2024/05/20 00:36

对一棵树的垂直遍历
这里写图片描述
http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

借助 hashMap实现

#include <iostream>#include <map>#include <algorithm>#include <vector>using namespace std;// A node of binary treestruct Node{    int data;    struct Node *left, *right;};// A utility function to create a new Binary Tree nodeNode* newNode(int data){    Node *temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;}// A utility function to find min and max distances with respect// to root.void findMinMax(Node *node, int *min, int *max, int hd){    // Base case    if (node == NULL) return;    // Update min and max    if (hd < *min) *min = hd;    else if (hd > *max) *max = hd;    // Recur for left and right subtrees    findMinMax(node->left, min, max, hd-1);    findMinMax(node->right, min, max, hd+1);}// A utility function to print all nodes on a given line_no.// hd is horizontal distance of current node with respect to root.void printVerticalLine(Node *node, int line_no, int hd){    // Base case    if (node == NULL) return;    // If this node is on the given line number    if (hd == line_no)        cout << node->data << " ";    // Recur for left and right subtrees    printVerticalLine(node->left, line_no, hd-1);    printVerticalLine(node->right, line_no, hd+1);}// The main function that prints a given binary tree in// vertical ordervoid verticalOrder(Node *root){    // Find min and max distances with resepect to root    int min = 0, max = 0;    findMinMax(root, &min, &max, 0);    // Iterate through all possible vertical lines starting    // from the leftmost line and print nodes line by line    for (int line_no = min; line_no <= max; line_no++)    {        printVerticalLine(root, line_no, 0);        cout << endl;    }}void VerticalHashMap(Node *node, int hd, map<int, int>& hM){    if (node == NULL) return;    if (hM.end() == hM.find(hd))        hM.insert(map<int, int>::value_type(hd, node->data));    else {        hM.at(hd) += node->data;    }    VerticalHashMap(node->left, hd-1, hM);    VerticalHashMap(node->right, hd+1, hM);}void printVerticalSum(Node* root) {    map<int, int> hM;    VerticalHashMap(root, 0, hM);    for (auto tmp : hM) {        cout << tmp.second << endl;    }}// Driver program to test above functionsint main(){    // Create binary tree shown in above figure    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";    verticalOrder(root);    cout << "Vertical sum is \n";    printVerticalSum(root);    system("pause");    return 0;}