314. Binary Tree Vertical Order Traversal

314. Binary Tree Vertical Order Traversal


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 1:

Input: [3,9,20,null,null,15,7]

   3
  /\
 /  \
 9  20
    /\
   /  \
  15   7 

Output:

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

Examples 2:

Input: [3,9,8,4,0,1,7]

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7 

Output:

[
  [4],
  [9],
  [3,0,1],
  [8],
  [7]
]

Examples 3:

Input: [3,9,8,4,0,1,7,null,null,null,2,5] (0’s right child is 2 and 1’s left child is 5)

     3
    /\
   /  \
   9   8
  /\  /\
 /  \/  \
 4  01   7
    /\
   /  \
   5   2

Output:

[
  [4],
  [9,5],
  [3,0,1],
  [8,2],
  [7]
]

方法1:

用BFS遍历,并将高度Hd 和 Node * 存入hash table
https://www.youtube.com/watch?v=PQKkr036wRc

易错点:

  1. 注意queue里面是pair<int, TreeNode*>, 要用myQueue.front().firstmyQueue.front().second来获取
  2. 这里用dfs遍历会有一个顺序问题:高层的按照要求应该先放入但是这个层级顺序在dfs中不好掌握,除非用双map存一下x,y坐标。
class Solution {
public:
    vector<vector<int>> verticalOrder(TreeNode* root) {
        if (!root) return {};
        map<int, vector<int>> hash;
        queue<pair<TreeNode*, int>> q;
        q.push(make_pair(root, 0));
        while (!q.empty()) {
            TreeNode* top = q.front().first;
            int pos = q.front().second;
            q.pop();
        
            hash[pos].push_back(top -> val);
            
            if (top -> left) q.push(make_pair(top -> left, pos - 1));
            if (top -> right) q.push(make_pair(top -> right, pos + 1));
        }
        vector<vector<int>> res;
        for (auto item: hash) res.push_back(item.second);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值