LeetCode 314. Binary Tree Vertical Order Traversal

来源:互联网 发布:违反交通淘宝 编辑:程序博客网 时间:2024/06/03 11:48

HashMap is key to solve this problem.


#include <iostream>#include <vector>#include <unordered_map>using namespace std;struct TreeNode {  int val;  TreeNode* right;  TreeNode* left;  TreeNode(int x): val(x), right(NULL), left(NULL) {}};/* Tree was set as below.        1      2   3    4   5*/TreeNode* setUpTree() {  TreeNode* root = new TreeNode(1);  TreeNode* tmp = root;  tmp->left = new TreeNode(2);  tmp->right = new TreeNode(3);  tmp = tmp->left;  tmp->left = new TreeNode(4);  tmp->right = new TreeNode(5);  return root;}void printInOrderTree(TreeNode* root) {  if(!root) return;  printInOrderTree(root->left);  cout << root->val << ", ";  printInOrderTree(root->right);}void VerticalOrder(TreeNode* root, int col, unordered_map<int, vector<int> >& res) {  if(!root) return;  else {    auto iter = res.find(col);    if(iter == res.end()) {      vector<int> tmp;      tmp.push_back(root->val);      res.insert(make_pair(col, tmp));    } else {      (iter->second).push_back(root->val);    }    VerticalOrder(root->left, col - 1, res);    VerticalOrder(root->right, col + 1, res);  }}void printVerticalOrder(vector< vector<int> >& res) {  for(int i = 0; i < res.size(); ++i) {    for(int j = 0; j < res[i].size(); ++j) {      cout << res[i][j] << " ";    }    cout << endl;  }}// since we want to group all the nodes in vertical order, seems hashMap is quite necessary.vector< vector<int> > VerticalOrder(TreeNode* root) {  unordered_map<int, vector<int> > res;  VerticalOrder(root, 0, res);  vector< vector<int> > result;  auto iter = res.begin();  while(iter != res.end()) {    result.push_back(iter->second);    iter++;  }  return result;}int main(void) {  TreeNode* root = setUpTree();  cout << "InOrder Traversal: " << endl;  printInOrderTree(root);  cout << endl;  cout << "Vertical Order Traversal: " << endl;  vector< vector<int> > res = VerticalOrder(root);  printVerticalOrder(res);  cout << endl;}

0 0
原创粉丝点击