Leetcode 107 Binary Tree Level Order Traversal II 二叉树+BFS
题意是倒过来层次遍历二叉树
下面我介绍下BFS的基本框架,所有的BFS都是这样写的
struct Nodetype { int d;//层数即遍历深度 KeyType m;//相应的节点值 } queue<Nodetype> q; q.push(firstnode); while(!q.empty()){ Nodetype now = q.front(); q.pop(); ........ for(遍历所有now点的相邻点next){ if(!visit[next]) { 访问每个没有访问过的点; 做相应的操作; next.d = now.d + 1; q.push(next); } } }
对于二叉树将val看成层数,这边我偷懒了。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> levelOrderBottom(TreeNode* root) { 13 14 vector<vector<int>> v; 15 if(!root) return v; 16 vector<int> t; 17 18 t.push_back(root->val); 19 v.push_back(t); 20 root->val = 1; 21 22 queue<TreeNode*> q; 23 q.push(root); 24 25 while(!q.empty()){ 26 TreeNode* now = q.front(); 27 q.pop(); 28 if(!now) continue; 29 30 q.push(now->left); 31 q.push(now->right); 32 if(now->val < v.size()){ 33 if(now->left) v[now->val].push_back(now->left->val); 34 if(now->right) v[now->val].push_back(now->right->val); 35 } 36 else{ 37 vector<int> t; 38 if(now->left) t.push_back(now->left->val); 39 if(now->right) t.push_back(now->right->val); 40 if(t.size() != 0)v.push_back(t); 41 } 42 if(now->left) now->left->val = now->val + 1; 43 if(now->right)now->right->val = now->val + 1; 44 } 45 reverse(v.begin(),v.end()); 46 return v; 47 } 48 };