题目:
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
return its level order traversal as:
1 2 3 4 5
| [ [3], [9,20], [15,7] ]
|
方法一:广度优先遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { return BFS(root); } private: vector<vector<int>> BFS(TreeNode* root) { if(!root) return {}; vector<vector<int>> ans; vector<TreeNode*> curr,next; curr.push_back(root); while(!curr.empty()) { ans.push_back({}); for(TreeNode* node : curr){ ans.back().push_back(node->val); if(node->left) next.push_back(node->left); if(node->right) next.push_back(node->right); } curr.swap(next); next.clear(); } return ans; } };
|
Status | Runtime | Language |
---|
Accepted | 4ms | cpp |
方法二:深度优先遍历
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; DFS(root,0,ans); return ans; } private: void DFS(TreeNode* root, int depth, vector<vector<int>>& ans) { if(!root) return; while(ans.size()<=depth) ans.push_back({}); DFS(root->left, depth+1, ans); DFS(root->right, depth+1, ans); ans[depth].push_back(root->val); } };
|
Status | Runtime | Language |
---|
Accepted | 4ms | cpp |