剑指offer 把二叉树打印成多行

剑指offer 把二叉树打印成多行

  • 题目描述

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

  • C++解法
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/

struct TNode{
	TreeNode* node;
	int level;
	TNode(TreeNode* n, int l) :node(n), level(l){}
};

class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int>> ret;
            if (pRoot == NULL)
                return ret;
            TNode root(pRoot,1);

            queue<TNode> q;
            q.push(root);

            vector<int> a;
            int remember = 1;

            while (!q.empty()){
                TNode temp = q.front();
                if (temp.level != remember){
                    ret.push_back(a);
                    a.clear();
                    remember = temp.level;
                }
                a.push_back(temp.node->val);
                if (temp.node->left)
                    q.push(TNode(temp.node->left,temp.level+1));
                if (temp.node->right)
                    q.push(TNode(temp.node->right,temp.level+1));
                q.pop();

            }
            ret.push_back(a);
            return ret;
        }

};
弹钢琴的猫 /
Published under (CC) BY-NC-SA in categories 算法  tagged with 剑指offer