Leetcode - Binary Tree Level Order Traversal II

題目鏈接

Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:Given binary tree [3,9,20,null,null,15,7]

圖1-1 實例輸入

return its bottom-up level order traversal as:

圖1-2 實例輸出

解題思路

TODO (稍后補上)

解題代碼

/**
 * 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) {
        vector<vector<TreeNode* >> output;
        vector<vector<int>> values;
        if (0 == root) {
            return values;
        }
        TreeNode* broot = root;
        vector<TreeNode* > tmp;
        vector<int> vtmp;
        tmp.push_back(broot);
        vtmp.push_back(broot->val);
        output.push_back(tmp);
        values.push_back(vtmp);
        int index = 0;
        while(index < output.size()) {
            vector<TreeNode* > cur;
            vector<int> vcur;
            for(int i=0;i<output[index].size();i++) {
                if(output[index][i]->left != 0) {
                    cur.push_back(output[index][i]->left);
                    vcur.push_back(output[index][i]->left->val);
                    cout << output[index][i]->left->val<<" ";
                }
                if(output[index][i]->right != 0) {
                    cur.push_back(output[index][i]->right);
                    vcur.push_back(output[index][i]->right->val);
                    cout << output[index][i]->right->val << " ";
                }
            }
            if(cur.size()!=0) {
                output.push_back(cur);
                values.push_back(vcur);
            }
            index++;
        }
        vector<vector<int>> re_values;
        for(int k=values.size()-1;k>=0; --k) {
            re_values.push_back(values[k]);
        }
        return re_values;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容