Rrui的Leetcode刷題筆記(三)
阿新 • • 發佈:2018-12-12
102. 二叉樹的層次遍歷
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { TreeNode* p=root; vector<vector<int>> a; queue<TreeNode*> q; q.push(p); if(!p) return a; while(!q.empty()) { int size=q.size(); vector<int> b; while(size--) { p=q.front(); if(p->left) q.push(p->left); if(p->right) q.push(p->right); b.push_back(p->val); q.pop(); } a.push_back(b); } return a; } };