LintCode-二叉树的层次遍历 II

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出一棵二叉树 {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

按照从下往上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]
标签  Expand  


分析:就是层次遍历呀。。。

代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 
 
class Solution {
    /**
     * @param root : The root of binary tree.
     * @return : buttom-up level order a list of lists of integer
     */
public:
    vector> levelOrderBottom(TreeNode *root) {
        // write your code here
        vector > ret;
        if(root==nullptr)
            return vector >();
        vector cur;
        cur.push_back(root);
        ret.push_back(cur);
        while(true)
        {
            vector newCur;
            vector cur = ret.back();
            for(auto x:cur)
            {
                if(x->left)
                    newCur.push_back(x->left);
                if(x->right)
                    newCur.push_back(x->right);
            }
            if(newCur.size()>0)
                ret.push_back(newCur);
            else
                break;
        }
        reverse(ret.begin(),ret.end());
        vector > values;
        for(auto v:ret)
        {
            vector vals;
            for(auto t:v)
                vals.push_back(t->val);
            values.push_back(vals);
        }
        return values;
    }
};


你可能感兴趣的:(面试)