[LeetCode] 107. Binary Tree Level Order Traversal II

题目链接:传送门

Description

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],

    3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

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

Solution

题意:

给定一棵二叉树,输出从左到右自底向上的层次遍历

思路:

其实发现从左到右自顶向下的层次遍历比较好写,最后 reverse 即为所求

/**
 * 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:
    void dfs(TreeNode* root, int height, vector<vector<int>>& res) {
        if (!root)  return ;
        if (res.size() <= height) {
            res.push_back(vector<int>(1, root->val));
        } else {
            res[height].push_back(root->val);
        }
        dfs(root->left, height + 1, res);
        dfs(root->right, height + 1, res);
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        dfs(root, 0, res);
        reverse(res.begin(), res.end());
        return res;
    }
};
posted @ 2018-02-27 01:22  酒晓语令  阅读(71)  评论(0编辑  收藏  举报