Binary Tree Vertical Order Traversal | Leetcode

Binary Tree Vertical Order Traversal

My Submissions
Total Accepted: 649  Total Submissions: 2309  Difficulty: Medium

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Examples:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its vertical order traversal as:

[
  [9],
  [3,15],
  [20],
  [7]
]

Given binary tree [3,9,20,4,5,2,7],

    _3_
   /   \
  9    20
 / \   / \
4   5 2   7

return its vertical order traversal as:

[
  [4],
  [9],
  [3,5,2],
  [20],
  [7]
]

 思路:大致的思路是上来先bfs一遍,存储所有点的坐标。比较需要思考的是,如何在知道坐标的情况下,便捷的生成最后结果。假设每一个TreeNode的坐标都是(row,col),由于最后的结果是按照col来排序的。col相同的情况下,row从上到下,节点从左到右。于是在每一层遍历的时候,我们都可以存入一个map中。map的key是col,value是这一列的所有元素。由于上面的点一定会覆盖下面的点,所以同一列的情况下,越靠近顶越在前面。所以在BFS的时候我们可以放心的把节点存入相应的列的map中。又由于我们是从左到右的遍历,所以row相同情况下,左边一点的节点还是会在前面。
代码如下:
class Solution {
public:
	vector<vector<int>> verticalOrder(TreeNode* root) {
	    vector<vector<int>> result;
	    if (!root)
	        return result;
		map<int, pair<int, int>> pos;
		map<int,vector<int>> mp;
		//do bfs to traverse first
		queue<TreeNode*> que;
		que.push(root);
		mp[0].push_back(root->val);
		pos[root->val] = make_pair(0, 0);
		while (!que.empty()) {
			int size = que.size();
			for (int i = 0; i < size; i++) {
				TreeNode* cur = que.front();
				que.pop();
				int x = pos[cur->val].first;
				int y = pos[cur->val].second;
				if (cur->left) {
					que.push(cur->left);
					pos[cur->left->val] = make_pair(x + 1, y - 1);
					mp[y-1].push_back(cur->left->val);
				}
				if (cur->right) {
					que.push(cur->right);
					pos[cur->right->val] = make_pair(x + 1, y + 1);
					mp[y+1].push_back(cur->right->val);
				}
			}
		}

		//generate result
		for (auto &pair : mp) {
			result.push_back(pair.second);
		}
		return result;
	}
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值