【Leetcode | 5】二叉樹系列(十三)
阿新 • • 發佈:2019-03-16
traversal href first for binary {} while leet auto
一、
二、
五、二叉樹的垂直遍歷
題目:987. Vertical Order Traversal of a Binary Tree
C++ Soution 1:
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>> verticalTraversal(TreeNode* root) 13 { 14 map<int, vector<int> > m; 15 queue<pair<int, TreeNode*> > q; 16 q.push(make_pair(0, root)); 17 while(!q.empty()) 18 { 19 set<pair<int, int> > tmp; 20 int len = q.size(); 21 for (int i = 0; i < len; ++i) 22 { 23 auto p = q.front(); q.pop(); 24 tmp.insert(make_pair(p.first, p.second->val));25 if (p.second->left) q.push(make_pair(p.first - 1, p.second->left)); 26 if (p.second->right) q.push(make_pair(p.first + 1, p.second->right)); 27 } 28 29 for (auto p : tmp) m[p.first].push_back(p.second); 30 } 31 32 vector<vector<int> > res; 33 for (auto kv : m) res.push_back(kv.second); 34 return res; 35 } 36 };
【Leetcode | 5】二叉樹系列(十三)