有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。 给定二叉树的根结点root,请返回打印结果,

来源:互联网 发布:json转java实体对象 编辑:程序博客网 时间:2024/06/07 04:08


有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。

给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。




/*

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/


class TreePrinter {
public:
    vector<vector<int> > printTree(TreeNode* root) {
        // write code here
        vector<vector<int>> result;
        if(root==NULL) return result;
        queue<TreeNode*> q;
        q.push(root);
        TreeNode* last;
        TreeNode* nlast;
last=root;
        vector<int> tmp;
        while(!q.empty())
            {
                TreeNode *t=q.front();
                tmp.push_back(t->val);
              q.pop();
            
            if(t->left)
                    {
                    nlast=t->left;                  
                    q.push(t->left);
                }
            if(t->right)
                    {
                    nlast=t->right;
                    q.push(t->right);
                }
                if(t==last)
                    {
                    result.push_back(tmp);
                    tmp.clear();
                    last=nlast;
                }
        }
        return result;
    }
};
0 0
原创粉丝点击