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.

思路:

题目类似二叉树的宽度优先遍历,可以通过一个队列来实现。但是队列中的每个节点都需要增加一个数值表示层次(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;
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11820141
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞