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;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容