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;
        }
    };
  • 相关阅读:
    Kattis
    HDU
    回溯法理解
    算法第5章上机实践报告
    贪心算法理解
    [模板] Dijkstra(堆优化)算法求最短路 Apare_xzc
    【文件管理系统】 Apaer_xzc
    [CCF] 201403-2 窗口 Apare_xzc
    [CCF] 201412-2 Z字形扫描 Apare_xzc
    [CCF] 201503-5 最小花费 Apare_xzc
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3608764.html
Copyright © 2011-2022 走看看