|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Seawolf 于 2019-10-3 05:43 编辑
- 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],
- 3
- / \
- 9 20
- / \
- 15 7
- return its level order traversal as:
- [
- [3],
- [9,20],
- [15,7]
- ]
复制代码
- /**
- * 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>> levelOrder(TreeNode* root) {
- // return BFS(root);
- vector<vector<int>> ans;
- DFS(root,0, ans);
- return ans;
- }
- private:
- vector<vector<int>> BFS(TreeNode* root){
- vector<vector<int>> ans;
- if(root == NULL) return ans;
- vector<TreeNode*> cur, next;
- cur.push_back(root);
-
- while(!cur.empty()){
- ans.push_back({});
- for(TreeNode* node : cur){
- ans.back().push_back(node->val);
-
- if(node->left != NULL) next.push_back(node->left);
- if(node->right != NULL) next.push_back(node->right);
- }
-
- cur.swap(next);
- next.clear();
- }
-
- return ans;
- }
-
- void DFS(TreeNode* root , int depth, vector<vector<int>>& ans){
- if(root == NULL) 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);
- }
- };
复制代码
optimized DFS
- /**
- * 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>> levelOrder(TreeNode* root) {
- // return BFS(root);
- vector<vector<int>> ans;
- if(!root) return ans;
- DFS(root,0, ans);
- return ans;
- }
- private:
- void DFS(TreeNode* root , int depth, vector<vector<int>>& ans){
- if(root != NULL) {
- if(ans.size() > depth){
- ans[depth].push_back(root->val);
- }else{
- ans.push_back(vector <int>{root->val});
- }
- DFS(root->left, depth+1, ans);
- DFS(root->right,depth+1, ans);
- }
- }
- };
复制代码 |
|