【LeetCode】二叉树的层次遍历 II

2019-04-07  本文已影响0人  MyyyZzz

题目描述:

FDFD5B22-BB20-42E2-91A9-016D01E294FC.png

代码:递归,先按顺序遍历,再反转

/**
 * 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<int>> res;
        vector<vector<int>> res2;
        pre(root, 0, res);
        for(int i=res.size()-1; i>=0; i--)
        {
            res2.push_back(res[i]); 
        }
        return res2;
    }
    
    void pre(TreeNode* root, int depth, vector<vector<int>> &res)
    {
        if(!root)
            return;
        if(depth>=res.size())
            res.push_back(vector<int>());
        res[depth].push_back(root->val);
        pre(root->left, depth+1, res);
        pre(root->right, depth+1, res);
    }
};
上一篇下一篇

猜你喜欢

热点阅读