LeetCode题目:Binary Tree Level Order Traversal II

By | 2012 年 12 月 8 日

和上一题差不多,只不过最后输出的时候颠倒一下,另外:std::list才有push_front(),而std::vector没有这个方法。



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],
]



代码:40ms过大集合

/**
 * 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 > levelOrderBottom(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        list > retTemp;

        queue trace;
        trace.push(root);
        trace.push(NULL);
        
        vector curLevel;
        while(true) {
            TreeNode *cur = trace.front();
            trace.pop();
            if(cur) {
                curLevel.push_back(cur->val);
                if(cur->left) trace.push(cur->left);
                if(cur->right) trace.push(cur->right);
            } else {
                if(curLevel.size()) {
                    retTemp.push_front(curLevel);
                    curLevel.erase(curLevel.begin(),curLevel.end());
                    trace.push(NULL);
                } else {
                    break;
                }
            }
        }
        
        vector > ret;
        for(list >::iterator it = retTemp.begin(); it != retTemp.end(); ++it) {
            ret.push_back(*it);
        }
        return ret;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注