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],

  /\
/ \ /\
/ \

return its vertical order traversal as:

[
[],
[,],
[],
[]
]

Given binary tree [3,9,8,4,0,1,7],

    /\
/ \ /\ /\
/ \/ \

return its vertical order traversal as:

[
[],
[],
[,,],
[],
[]
]

Given binary tree [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),

    /\
/ \ /\ /\
/ \/ \ /\
/ \

return its vertical order traversal as:

[
[],
[,],
[,,],
[,],
[]
]

思路:bsf。然后用链表暂时存储结果。假设当前链表节点的iterator为it,则它的前一个节点的iterator可以用std::prev(it, 1)获得,它的下一个节点的iterator可以用std::next(it, 1)获得。

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int> > res;
if (root == NULL) return res;
list<vector<int> > columns;
queue<TreeNode*> nodes;
queue<list<vector<int> >::iterator> iterators;
columns.push_back(vector<int>(, root->val));
nodes.push(root);
iterators.push(columns.begin());
while (!nodes.empty()) {
TreeNode* cur = nodes.front(); nodes.pop();
auto it = iterators.front(); iterators.pop();
if (cur->left) {
if (it == columns.begin()) columns.push_front(vector<int>(, cur->left->val));
else std::prev(it, )->push_back(cur->left->val);
nodes.push(cur->left);
iterators.push(std::prev(it, ));
}
if (cur->right) {
if (std::next(it, ) == columns.end()) columns.push_back(vector<int>(, cur->right->val));
else std::next(it, )->push_back(cur->right->val);
nodes.push(cur->right);
iterators.push(std::next(it, ));
}
}
for (auto it = columns.begin(); it != columns.end(); it++)
res.push_back(*it);
return res;
}
};
05-11 19:38