Skip to content

Latest commit

 

History

History
executable file
·
118 lines (62 loc) · 4.01 KB

107. Binary Tree Level Order Traversal II.md

File metadata and controls

executable file
·
118 lines (62 loc) · 4.01 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

##(一)题目

来源: https://leetcode.com/problems/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] ,

3 /
9 20 /
15 7

return its bottom-up level order traversal as:

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

##(二)解题

本题大意:按层序从下往上输出二叉树,注意与 【一天一道LeetCode】#102. Binary Tree Level Order Traversal

解题思路:在上一题的基础上,我偷懒的用了一个resverse函数就将结果反过来输出了。

代码如下:

/**

 * 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>> ret;

        if(root==NULL) return ret;

        queue<TreeNode*> que;//用queue来存储每一层的节点

        que.push(root);//初始化

        while(!que.empty())

        {

            vector<int> tempVec;

            queue<TreeNode*> tempque;

            while(!que.empty())//依次取出节点

            {

                TreeNode* tempNode = que.front();//从左往右

                que.pop();

                tempVec.push_back(tempNode->val);

                if(tempNode->left!=NULL) tempque.push(tempNode->left);//处理左子树

                if(tempNode->right!=NULL) tempque.push(tempNode->right);//处理右子树

            }

            que = tempque;//que赋值为下一层的节点

            ret.push_back(tempVec);//每一层的结果保存下来

        }

        reverse(ret.begin(),ret.end());//反向

        return ret;

    }

};