[leetcode] Vertical Order Traversal of a Binary Tree
Posted 荒废的养鸡场
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] Vertical Order Traversal of a Binary Tree相关的知识,希望对你有一定的参考价值。
1. Traverse the binary tree, store {x,y,val} for every node in records;
2. Sort the records of {x,y,val} for all nodes by increasing x, decreasing y, and increasing val order;
3. Traverse the sorted records, for elements that have same x, put their vals in a vector one by one then push the vector in the answer to return;
struct x_y_val { int x; int y; int val; x_y_val(int _x, int _y, int _val):x(_x),y(_y),val(_val) {} }; bool cmp (x_y_val a, x_y_val b) { if (a.x<b.x) return true; if (a.x==b.x&&a.y>b.y) return true; if (a.x==b.x&&a.y==b.y&&a.val<b.val) return true; return false; } class Solution { public: //need to consider y, not only x. void mark_x_y(TreeNode* root, int x, int y, vector<x_y_val>& records) { if (root==NULL) return; records.push_back(x_y_val(x,y, root->val)); mark_x_y(root->left, x-1, y-1, records); mark_x_y(root->right, x+1, y-1, records); } vector<vector<int>> verticalTraversal(TreeNode* root) { vector<vector<int>> answer; if (root==NULL) return answer; vector<x_y_val> records; mark_x_y(root, 0,0, records); sort(records.begin(), records.end(), cmp); vector<int> temp; int last_x=records[0].x; for (auto current:records) { if (current.x!=last_x) { answer.push_back(temp); temp.clear(); last_x=current.x; } temp.push_back(current.val); } answer.push_back(temp); return answer; } };
wow, i know it‘s poor though.
以上是关于[leetcode] Vertical Order Traversal of a Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 314. Binary Tree Vertical Order Traversal
Leetcode 314: Binary Tree Vertical Order Traversal
[LeetCode] 314. Binary Tree Vertical Order Traversal
[LeetCode] 314. Binary Tree Vertical Order Traversal