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]
]
思路:
1. 肯定是使用遍历。在遍历过程中,对每一个node标记应该的column number。往左子树遍历,则column number-1;往右子树遍历,则column number+1。用map保存有相同tag的node!
2. 学会思考,树的问题,就是遍历,遍历过程中可以获取很多信息,利用树的结构,看如何获取信息是效率最高,最简单!
vector<vector<int>> verticalOrder(TreeNode* root) {
map<int,vector<int>> mm;
dfs(root,mm,0);
vector<vector<int>> res;
for(auto it:mm){
res.push_back(it.second);
}
return res;
}
void dfs(TreeNode* root,map<int,vector<int>>&mm,int column){
if(!root) return;
mm[tag].push_back(root->val);
dfs(root->left,mm,column-1);
dfs(root->right,mm,column+1);
}