[劍指offer]把二叉樹列印成多行
阿新 • • 發佈:2019-01-08
題目描述
從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。 分析:層序遍歷用佇列,這道題比較討厭的是要把每層分開,如果只是單純把值全部打印出來,只要判斷佇列是否為空就可以了,這裡需要判斷已經列印的個數是不是這一層的總個數。程式碼:
/* 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) { queue<TreeNode*> q; vector<vector<int> > ret; if(pRoot==NULL) return ret; q.push(pRoot); helper(ret,q); return ret; } void helper(vector<vector<int> > &ret,queue<TreeNode*> &q){ while(!q.empty()){ vector<int> path; int n=q.size(); int i=0; while(i<n){ TreeNode* temp=q.front(); path.push_back(temp->val); if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); q.pop(); i++; } ret.push_back(path); } } };