1. 程式人生 > >劍指offer—把二叉樹列印成多行

劍指offer—把二叉樹列印成多行

華電北風吹
天津大學認知計算與應用重點實驗室
日期:2015/10/8

題目描述
從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。

解析:這個跟按行列印一樣的思路即可。

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector
<int>
>
Print(TreeNode* pRoot) { vector<vector<int>> result; if (pRoot == NULL) return result; vector<int> temp; TreeNode * flag = new TreeNode(NULL); queue<TreeNode *> q; q.push(pRoot); q.push(flag); while
(true) { TreeNode * top = q.front(); q.pop(); if (top == flag) { result.push_back(temp); temp.clear(); q.push(top); top = q.front(); q.pop(); if (top == flag) break
; } temp.push_back(top->val); if (top->left != NULL) q.push(top->left); if (top->right != NULL) q.push(top->right); } return result; } };