高级农民
积分 1550
大米 颗
鳄梨 个
水井 尺
蓝莓 颗
萝卜 根
小米 粒
学分 个
注册时间 2014-10-12
最后登录 1970-1-1
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本帖最后由 codedayday 于 2021-1-30 18:30 编辑
欢迎去下面讨论:
https://leetcode.com/problems/ve ... th-the-end-in-mind- (%22The-7-Habits-of-Highly-Effective-People%22)
或者我贴在这里,非常欢迎大家的意见。
DFS = Begin with the end in mind ("The 7 Habits of Highly Effective People")
One of hard part to understand recursion function is that when you creat a dfs function and you need assume dfs is already there good to be used.
It is a wonderful chick-egg dilemma.
class Solution {
public:
vector<vector<int>> verticalTraversal(TreeNode* root) {
map<int, map<int, multiset<int> > > m;
dfs(root, 0, 0, m); // step1: consume dfs function first
vector<vector<int>> ans;
for(auto& [col, rowAndVals]: m){ // step 2: consume m and begin with smallest/leftmost col index
vector<int> rowVec;
for(auto& [row, Vals]: rowAndVals) // step 3: top-down and begin with smallest/topmost row index
rowVec.insert(rowVec.end(), Vals.begin(), Vals.end());//step 4: multiset is used to ensure order
ans.push_back(rowVec);
}
return ans;
}
private: // step 4: pre-order traverse binary tree and log
void dfs(TreeNode* root, int row, int col, map<int, map<int, multiset<int> > >& m){
if(!root) return;
m[col][row].insert(root->val);
dfs(root->left, row + 1, col - 1, m);
dfs(root->right, row + 1, col + 1, m);
}
}; 复制代码
上一篇:
关于CS61a 下一篇:
有人组队一起刷leetcode么