标签:哈希 二叉树遍历 二叉树垂直遍历 垂直打印 二叉树垂直打印
        /           2      3
      / \      /     4   5   6   7
               \                  8   9 
对这棵树的垂直遍历结果为:
4
2
1 5 6
3 8
7
9
在二叉树系列中,已经讨论过了一种O(n2)的方案。在本篇中,将讨论一种基于哈希表的更优的方法。首先在水平方向上检测所有节点到root的距离。如果两个node拥有相同的水平距离(Horizontal Distance,简称HD), 则它们在相同的垂直线上。root自身的HD为0,右侧的node的HD递增,即+1,而左侧的node的HD递减,即-1。例如,上面的那棵树中,Node4的HD为-2, 而Node5和Node6的HD为0,Node7的HD为2.。
下面是上述方法的C++实现。
<span style="font-size:12px;">// C++程序:垂直的打印一棵二叉树
#include <iostream>
#include <vector>
#include <map>
//二叉树的节点
struct Node
{
    int key;
    Node *left;
    Node *right;
};
//创建一个新的节点
Node* newNode(int key)
{
    Node* node = new Node;
    node->key = key;
    node->left = node->right = NULL;
    return node;
}
// 将垂直排序的节点存入哈希表m中;
// 参数distance表示当前节点到root的HD距离。初始值为0
void getVerticalOrder(Node* root, int distance, std::map<int, std::vector<int> > &result)
{
    // 检测特定情况
    if (root == NULL)
        return;
    // 将当前node存入map中
    result[distance].push_back(root->key);
    // 递归存储左子树。 注意:距离值是递减的
    getVerticalOrder(root->left, distance-1, result);
    // 递归存储右子树。注意:距离值是递增的
    getVerticalOrder(root->right, distance+1, result);
}
// 按照垂直顺序打印二叉树的节点
void printVerticalOrder(Node* root)
{
    //map存储所有垂直排序的节点
    std::map <int, std::vector<int> > result;
    int distance = 0;
    getVerticalOrder(root, distance, result);
    //遍历map,进行打印
    std::map< int,std::vector<int> > :: iterator it;
    for (it=result.begin(); it!=result.end(); it++)
    {
        for (unsigned int i=0; i<it->second.size(); ++i)
            std::cout << it->second[i] << " ";
        std::cout << std::endl;
    }
}
Node* generateBST()
{
  /* 构建二叉树树
         1
      /         2      3
    / \    /    4   5  6   7
           \               8   9
   */
  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);
  return root;
}
int main()
{
    Node *root = generateBST();
    std::cout << "Vertical order traversal is:"<<std::endl;
    printVerticalOrder(root);
    return 0;
}
</span>输出:标签:哈希 二叉树遍历 二叉树垂直遍历 垂直打印 二叉树垂直打印
原文地址:http://blog.csdn.net/shltsh/article/details/46383151