Monday, August 7, 2017

[Leetcode] Binary Tree Vertical Order Traversal, Solution

Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).
If two nodes are in the same row and column, the order should be from left to right.
Examples:
  1. Given binary tree [3,9,20,null,null,15,7],
       3
      /\
     /  \
     9  20
        /\
       /  \
      15   7
    
    return its vertical order traversal as:
    [
      [9],
      [3,15],
      [20],
      [7]
    ]
    
  2. Given binary tree [3,9,8,4,0,1,7],
         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
    
    return its vertical order traversal as:
    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]
    
  3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5),
         3
        /\
       /  \
       9   8
      /\  /\
     /  \/  \
     4  01   7
        /\
       /  \
       5   2
    
    return its vertical order traversal as:
    [
      [4],
      [9,5],
      [3,0,1],
      [8,2],
      [7]
    ]
    
[Thoughts]
这题挺有意思的。其实就是做一个按层遍历(http://fisherlei.blogspot.com/2013/01/leetcode-binary-tree-level-order.html),只不过在遍历的过程中,同时对于每一个节点记录其vertical index,放到map中去做统计。

[Code]

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:    map<int, vector<int>> record;  
13:      
14:    vector<vector<int>> verticalOrder(TreeNode* root) {  
15:      seqOrder(root);  
16:      vector<vector<int>> result;  
17:      for(auto rec : record) {  
18:        result.push_back(rec.second);  
19:      }  
20:      return result;  
21:    }  
22:      
23:    void seqOrder(TreeNode* root) {  
24:      queue<TreeNode*> visit;  
25:      queue<int> vertical_index;  
26:        
27:      if(root == NULL) return;  
28:      visit.push(root);  
29:      vertical_index.push(0);  
30:      while(visit.size() >0) {  
31:        TreeNode* node = visit.front();  
32:        int cur_in = vertical_index.front();  
33:        visit.pop();  
34:        vertical_index.pop();  
35:          
36:        record[cur_in].push_back(node->val);  
37:          
38:        if(node->left != NULL) {  
39:          visit.push(node->left);  
40:          vertical_index.push(cur_in -1);  
41:        }  
42:          
43:        if(node->right != NULL) {  
44:          visit.push(node->right);  
45:          vertical_index.push(cur_in +1);  
46:        }  
47:      }   
48:    }  
49:  };  



No comments: