把二叉树打印成多行 c++

题目描述

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

/*

struct TreeNode {

   int val;

   struct TreeNode *left;

   struct TreeNode *right;

   TreeNode(int x) :

           val(x), left(NULL), right(NULL) {

    }

};

*/

class Solution {

public:

       vector > Print(TreeNode* pRoot) {

            vector item;

           vector > result;

           if(pRoot==NULL) return result;

           queue > Q;

           Q.push(make_pair(pRoot,1));

           int old_deep=0;

           while(!Q.empty())

           {

                TreeNode* node=Q.front().first;

                int deep=Q.front().second;

                Q.pop();

                if(item.size()==0)

                {

                   item.push_back(node->val);

                    old_deep=deep;

                }else

                {

                    if(old_deep!=deep)

                    {

                        result.push_back(item);

                        item.clear();

                       item.push_back(node->val);

                        old_deep=deep;

                    }else

                    {

                       item.push_back(node->val);

                    }

                }

                if(node->left)

                {

                   Q.push(make_pair(node->left,deep+1));

                }

                if(node->right)

                {

                   Q.push(make_pair(node->right,deep+1));

                }

           }

           if(item.size()!=0)

           {

                result.push_back(item);

           }

           return result;

       }

   

};

 

你可能感兴趣的:(牛客网)