码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer59-把二叉树打印成多行

时间:2020-05-29 17:48:51      阅读:45      评论:0      收藏:0      [点我收藏+]

标签:turn   nod   esc   int start   cto   item   while   title   queue   

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:层次遍历

    vector<vector<int> > Print(TreeNode* pRoot) {
           vector<vector<int> > vec;
            if(pRoot == NULL) return vec;
            queue<TreeNode*> q;
            q.push(pRoot);
 
            while(!q.empty())
            {
                int start = 0, end = q.size();
                vector<int> c;
                while(start++ < end)
                {
                    TreeNode *t = q.front();
                    q.pop();
                    c.push_back(t->val);
                    if(t->left) q.push(t->left);
                    if(t->right) q.push(t->right);
                }
                vec.push_back(c);
            }
            return vec;
        }

剑指offer59-把二叉树打印成多行

标签:turn   nod   esc   int start   cto   item   while   title   queue   

原文地址:https://www.cnblogs.com/trouble-easy/p/12988482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!