LeetCode | 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.

考え方:

題は二叉木のような幅を優先して遍歴し,1つのキューで実現できる.しかし、キュー内の各ノードには、数値表示階層(level)を追加する必要があります.隣接する階層を区別するだけなので、階層をlevel%2またはbool値に簡略化して表すことができます.アルゴリズム類似http://blog.csdn.net/lanxu_yy/article/details/11820189を選択します.

コード:

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        TreeNode * q1[10000];
        bool q2[10000];
        int begin=0;
        int end=0;
        
        if(root == NULL)
        {
            vector<vector<int> > v;
            return v;
        }
        else
        {
            vector<vector<int> > v;
            q1[end] = root;
            q2[end++] = true;
            
            bool level = true;
            
            vector<int> * tmp = new vector<int>();
            while(begin!=end)
            {
                TreeNode * p = q1[begin];
                bool cur = q2[begin++];
                
                if(cur != level)
                {
                    v.push_back(*tmp);
                    delete tmp;
                    tmp = new vector<int>();
                    level = !level;
                    
                }
                if(cur == level)
                {
                    if(p->left != NULL)
                    {
                        q1[end] = p->left;
                        q2[end++] = !cur;
                    }
                    if(p->right != NULL)
                    {
                        q1[end] = p->right;
                        q2[end++] = !cur;
                    }
                    tmp->push_back(p->val);
                }
                
            }
            v.push_back(*tmp);
            for(int i = 0; i < v.size() / 2; i++)
            {
                vector<int> t = v[i];
                v[i] = v[v.size() - 1 - i];
                v[v.size() - 1 - i] = t;
            }
            return v;
        }
    }
};