二叉树打印

二叉树打印

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

"二叉树按层打印-0"

"二叉树按层打印-1"

"二叉树按层打印-2"

/*
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
        TreeNode *last,*nlast,*current;
        vector<int> row;
        vector< vector<int>> res;
        queue<TreeNode*> q;
        last=root;
        nlast=root;
        q.push(root);
        while (!q.empty())
        {
            current=q.front();
            if(current->left){
                q.push(current->left);
                nlast=current->left;
            }
            if(current->right){
                q.push(current->right);
                nlast=current->right;
            }

            row.push_back(current->val);
             if(last==current){
                last=nlast;
                res.push_back(row);
                row.clear();
            }
            q.pop();
        }
        return res;
    }
};
文章目录
  1. 1. 二叉树打印
|