Created
July 20, 2019 17:46
-
-
Save zhangxiaomu01/07b09aa5b8ea0ad7ee6ec9d871e754ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
private: | |
void dfs(vector<vector<int>>& res, TreeNode* node, int level){ | |
int len = res.size(); | |
//How to maintain the current layer list is critical here. | |
if(res.empty() || len < level + 1) | |
res.push_back(vector<int>()); | |
res[level].push_back(node->val); | |
if(node->left) dfs(res, node->left, level+1); | |
if(node->right) dfs(res, node->right, level + 1); | |
} | |
public: | |
vector<vector<int>> levelOrder(TreeNode* root) { | |
vector<vector<int>> res; | |
if(!root) return res; | |
dfs(res, root, 0); | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment