[leetcode] 107. Binary Tree Level Order Traversal II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/86677974

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

分析

  • 这道题目用了BFS,进行层序遍历,用队列来实现这一过程。然后用vector装结果,由于题目要求自底向上,我们是自顶向下求的,因此我们需要把顺序翻转一下。

代码

/**
 * 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;
        if(!root){
            return res;
        }
        queue<TreeNode*> q;
        TreeNode* tmp;
        q.push(root);
        while(!q.empty()){
            int t=q.size();
            vector<int> v;
            for(int i=0;i<t;i++){
                tmp=q.front();
                q.pop();
                v.push_back(tmp->val);
                if(tmp->left){
                    q.push(tmp->left);
                }
                if(tmp->right){
                    q.push(tmp->right);
                }
            }
            res.push_back(v);
        }
        reverse(res.begin(),res.end());
        return res;
    }
   
};

参考文献

[编程题]binary-tree-level-order-traversal-ii

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/86677974