leetcode 107 Binary Tree Level Order Traversal II

给定二叉树,从左到右遍历每层,在从下到上遍历。

解决:

BFS

vector<vector<int>> levelOrderBottom(TreeNode* root) {
    if (root == NULL)
        return vector<vector<int> >();
    
    vector<vector<int> > ret;
    deque<TreeNode*> now;
    now.push_back(root);
    
    while (now.size()) {
        int size = now.size();
        vector<int> ins;
        for (int i = 0; i < size; ++i) {
            TreeNode* n = now.front();
            now.pop_front();
            ins.push_back(n->val);
            if (n->left)
                now.push_back(n->left);
            if (n->right)
                now.push_back(n->right);
        }
        ret.push_back(move(ins));
    }
    reverse(ret.begin(), ret.end());
    return move(ret);
}

由于数据量大,move增速明显。

DFS

vector<vector<int>> levelOrderBottom(TreeNode* root) {
    vector<vector<int>> list={};
    dfs(list,root,1);     
    reverse(list.begin(),list.end());
    return list;
}

void dfs(vector<vector<int>> &list, TreeNode * root, int depth){
    if(root==NULL)
        return;
    if(list.size()<depth)
        list.resize(depth);      
    list[depth-1].push_back(root->val);
    
    dfs(list,root->left,depth+1);
    dfs(list,root->right,depth+1);
}

 

posted on 2018-01-24 01:19  willaty  阅读(107)  评论(0编辑  收藏  举报

导航