zoukankan      html  css  js  c++  java
  • 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,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    
    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

    思路:此题和Binary Tree Level Order Traversal是类似的,就是输出的顺序改变了,在上题的基础之上,我将顺序颠倒输出就可以了。

    /**
     * Definition for binary tree
     * 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> > result;
            if(root==NULL)
                return result;
            queue<TreeNode *> pTree;
            vector<int> data;
            pTree.push(root);
            int count=1;
            while(!pTree.empty())
            {
                data.clear();
                int temp_count=0;
                for(int i=0;i<count;i++)
                {
                    TreeNode *tn=pTree.front();
                    pTree.pop();
                    data.push_back(tn->val);
                    if(tn->left)
                    {
                        pTree.push(tn->left);
                        temp_count++;
                    }
                    if(tn->right)
                    {
                        pTree.push(tn->right);
                        temp_count++;
                    }
                }
                count=temp_count;
                result.push_back(data);
            }
            vector<vector<int> > ret;
            vector<vector<int> >::iterator iter=result.end()-1;
            for(;iter>=result.begin();iter--)
            {
                ret.push_back(*iter);
            }
            return ret;
        }
    };
  • 相关阅读:
    CCF_2014_09_2_画图
    计蒜课_等和分隔子集
    计蒜客_合法分数的组合
    读构建之法的读书笔记
    四则运算及感想
    psp 第二周
    第二周 词频统计
    历年作品点评
    四人小组项目
    品读《构建之法》及几个问题的提出
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3608764.html
Copyright © 2011-2022 走看看