← Home

987. Vertical Order Traversal of a Binary Tree

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
987

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 987. Vertical Order Traversal of a Binary Tree, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers.

The notes already sitting in the source point us in the right direction:

  • map, multiset(both are sorted)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//map, multiset(both are sorted)
02//Runtime: 4 ms, faster than 93.71% of C++ online submissions for Vertical Order Traversal of a Binary Tree.
03//Memory Usage: 14.9 MB, less than 11.43% of C++ online submissions for Vertical Order Traversal of a Binary Tree.
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15class Solution {
16public:
17    //(x, y) -> values
18    map<int, map<int, multiset<int>>> coord2values;
19    
20    void dfs(TreeNode* node, int x, int y){
21        if(node == nullptr) return;
22        
23        coord2values[x][y].insert(node->val);
24        
25        /*
26        from problem description,
27        we should use y-1 here,
28        but because we want it sort y in descending order,
29        we don't bother to change our data structure,
30        but here we change the definition of y
31        */
32        dfs(node->left, x-1, y+1);
33        dfs(node->right, x+1, y+1);
34    }
35    
36    vector<vector<int>> verticalTraversal(TreeNode* root) {
37        dfs(root, 0, 0);
38        
39        vector<vector<int>> ans;
40        
41        for(auto itx = coord2values.begin(); itx != coord2values.end(); ++itx){
42            vector<int> line;
43            for(auto ity = itx->second.begin(); ity != itx->second.end(); ++ity){
44                // cout << "(" << itx->first << ", " << ity->first << "): ";
45                // for(auto itn = ity->second.begin(); itn != ity->second.end(); ++itn){
46                //     cout << *itn << " ";
47                // }
48                // cout << endl;
49                line.insert(line.end(), ity->second.begin(), ity->second.end());
50            }
51            ans.push_back(line);
52        }
53        
54        return ans;
55    }
56};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.