LeetCode 314. Binary Tree Vertical Order Traversal

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值