107. Binary Tree Level Order Traversal II

仅供自己学习

 

直接和编号102的题一样的思路,直接最后reverse就行,基本得BFS方法即可

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrderBottom(TreeNode* root) {
13         queue<TreeNode*> q;
14         vector<vector<int>> res;
15         if(root)q.push(root);
16         while(!q.empty()){
17             int size = q.size();
18             vector<int> level;
19             while(size--){
20                 TreeNode* temp=q.front();
21                 q.pop();
22                 level.push_back(temp->val);
23                 if(temp->left) q.push(temp->left);
24                 if(temp->right) q.push(temp->right);
25             }
26             res.push_back(level);
27         }
28         reverse(res.begin(),res.end());
29         return res;
30     }
31 };

 

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>> levelOrderBottom(TreeNode* root) {
        if(!root) return {};
        vector<vector<int>> res;
        DFS(root,0,res);
        reverse(res.begin(),res.end());
        return res;
    }
    void DFS(TreeNode* root,int level,vector<vector<int>>& res){
        if(root==NULL) return;
        if(level==res.size()) res.push_back({});
        res[level].push_back(root->val);
        DFS(root->left,level+1,res);
        DFS(root->right,level+1,res);
    }
};

 

posted @ 2021-02-17 20:46  Mrsdwang  阅读(37)  评论(0)    收藏  举报