小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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},
1
return its bottom-up level order traversal as:
2

分析

LeetCode(103) Binary Tree Zigzag Level Order Traversal 以及 LeetCode(102) Binary Tree Level Order Traversal 本质相同的题目,只不过灵活调整结果返回格式罢了。

AC代码

/**
 * 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) {
        //层次遍历,分层存储
        if (!root)
            return vector<vector<int> >();

        vector<vector<int> > ret;

        //定义两个队列,一个存储所有的父节点,另一个存储他们的子节点也就是子层
        queue<TreeNode *> parents;

        parents.push(root);

        while (!parents.empty())
        {
            //存储当前层的遍历结果
            vector<int> tmp;
            //定义队列存储他们的子节点也就是子层
            queue<TreeNode *> childs;
            while (!parents.empty())
            {
                TreeNode *node = parents.front();
                tmp.push_back(node->val);
                //弹出当前父节点
                parents.pop();

                if (node->left)
                    childs.push(node->left);

                if (node->right)
                    childs.push(node->right);
            }
            //存储当前层的遍历结果
            ret.push_back(tmp);
            //遍历下一层
            parents = childs;
        }
        //反转遍历结果 由下向上存储
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

GitHub测试程序源码

posted on 2015-10-14 14:17  Coding菌  阅读(109)  评论(0编辑  收藏  举报