题解 | #从下到上打印二叉树#

从下到上打印二叉树

http://www.nowcoder.com/practice/ed982e032ff04d6a857b4cb4e6369d04

层次遍历+翻转数组:递归、非递归

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector<vector<>>
     */
    void bfs(TreeNode* root,int t,vector<vector<int> >& res){
        if(!root)return;
        if(t==res.size()){
            vector<int > tmp(1,root->val);
            res.push_back(tmp);
        }
        else{
            res[t].push_back(root->val);
        }
        
        bfs(root->left,t+1,res);
        bfs(root->right,t+1,res);
        return;
    }
    /*vector<vector<int> > levelOrderBottom(TreeNode* root) {
        // write code here
        vector<vector<int> > res;
        bfs(root,0,res);
        reverse(res.begin(),res.end());
        return res;
    }*/
    vector<vector<int> > levelOrderBottom(TreeNode* root) {
        // write code here
        vector<vector<int> > res;
        if(!root)return res;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int t=q.size();
            vector<int> tmp;
            while(t--){
                TreeNode* node=q.front();
                tmp.push_back(node->val);
                if(node->left)q.push(node->left);
                if(node->right)q.push(node->right);
                q.pop();
            }
            res.push_back(tmp);
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

alt

全部评论

相关推荐

白火同学:1、简历可以浓缩成一页,简历简历先要“简”方便HR快速过滤出有效信息,再要“历”用有效信息突出个人的含金量。 2、教育背景少了入学时间~毕业时间,HR判断不出你是否为应届生。 3、如果你的平台账号效果还不错,可以把账号超链接或者用户名贴到对应位置,一是方便HR知道你是具体做了什么内容的运营,看到账号一目了然,二是口说无凭,账号为证,这更有说服力。
面试被问期望薪资时该如何...
点赞 评论 收藏
分享
King987:待优化的地方还是挺多的,可以参考一下我的作品优化一下,优化不好的话也可以找我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务