Binary Tree Level Order Traversal II

思路同上题,不过在结束的时候用另一个vector把结果反向拷了出来。不知道有没有其他的办法。

vector<vector<int> > levelOrderBottom(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > result;
        result.clear();
        if(root == NULL)
            return result;
        vector<int> tmp;
        vector<TreeNode*> nodeVec;
        nodeVec.reserve(1000);
        nodeVec.push_back(root);
        vector<TreeNode*>::iterator head, tail;
        head = nodeVec.begin();
        tail = nodeVec.end()-1;
        while(!nodeVec.empty()){
            tmp.clear();
            while(head <= tail){
               tmp.push_back((*head)->val);
               if((*head)->left != NULL){
                   nodeVec.push_back((*head)->left);
               }
               if((*head)->right != NULL){
                   nodeVec.push_back((*head)->right);
               }
               head++;
            }
            result.push_back(tmp);
            nodeVec.erase(nodeVec.begin(), head);
            head = nodeVec.begin();
            tail = nodeVec.end()-1;
        }
        vector<vector<int> > resultBottom;
        int i, n = result.size();
        for(i = n-1; i >= 0; i--){
            resultBottom.push_back(result[i]);
        }
        return resultBottom;
    }

 

posted on 2013-09-30 10:37  waruzhi  阅读(180)  评论(0编辑  收藏  举报

导航