美文网首页
[Leetcode] 87. Binary Tree Level

[Leetcode] 87. Binary Tree Level

作者: 时光杂货店 | 来源:发表于2017-03-27 16:50 被阅读1次

    题目

    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,#,#,15,7},

     3
    / \
    9  20
      /  \
     15   7
    

    return its bottom-up level order traversal as:

    [
    [15,7],
    [9,20],
    [3]
    ]

    解题之法

    /**
     * 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;
            levelorder(root, 0, res);
            return vector<vector<int> > (res.rbegin(), res.rend());
        }
        void levelorder(TreeNode *root, int level, vector<vector<int> > &res) {
            if (!root) return;
            if (res.size() == level) res.push_back({});
            res[level].push_back(root->val);
            if (root->left) levelorder(root->left, level + 1, res);
            if (root->right) levelorder(root->right, level + 1, res);
        }
    };
    

    相关文章

      网友评论

          本文标题:[Leetcode] 87. Binary Tree Level

          本文链接:https://www.haomeiwen.com/subject/asmrottx.html