zoukankan      html  css  js  c++  java
  • 314. Binary Tree Vertical Order Traversal

    问题描述:

    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:

    Input: [3,9,20,null,null,15,7]
    
       3
      /
     /  
     9  20
        /
       /  
      15   7 
    
    Output:
    
    [
      [9],
      [3,15],
      [20],
      [7]
    ]
    

    Examples 2:

    Input: [3,9,8,4,0,1,7]
    
         3
        /
       /  
       9   8
      /  /
     /  /  
     4  01   7 
    
    Output:
    
    [
      [4],
      [9],
      [3,0,1],
      [8],
      [7]
    ]
    

    Examples 3:

    Input: [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
    
    Output:
    
    [
      [4],
      [9,5],
      [3,0,1],
      [8,2],
      [7]
    ]

    解题思路:

    这个题目要求竖着垂直输出树的节点。

    我们可以给每个节点按一个下标,然后用map来存储下标和数组,遍历到这个节点将这个节点的值加入到对应下标的数组中。

    因为我们要保证从上到下输出所以要选对正确的遍历方式,一开始我选择了普通的前序遍历,可以发现数字分组(即标下标)是正确的

    但是组内顺序不对。

    我们应该用层序遍历来处理。

    需要注意的是:

      在这里我们选择了用map存储,c++中map的键存储在树形结构,自动排序

    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> verticalOrder(TreeNode* root) {
            map<int, vector<int>> m;
            vector<vector<int>> ret;
            if(!root)
                return ret;
            traverse(root, 0, m);
            for(auto p:m){
                ret.push_back(p.second);
            }
            return ret;
        }
    private:
        void traverse(TreeNode* root, int idx, map<int, vector<int>> &m){
            queue<TreeNode*> node_q;
            queue<int> idx_q;
            node_q.push(root);
            idx_q.push(idx);
            while(!node_q.empty()){
                int curIdx = idx_q.front();
                idx_q.pop();
                TreeNode* cur = node_q.front();
                node_q.pop();
                m[curIdx].push_back(cur->val);
                if(cur->left){
                    node_q.push(cur->left);
                    idx_q.push(curIdx - 1);
                }
                if(cur->right){
                    node_q.push(cur->right);
                    idx_q.push(curIdx + 1);
                }
            }
        }
    };
  • 相关阅读:
    HDU 6043
    HDU 6033
    HDU 6041
    HDU 6050
    HDU 6053
    HDU 6055
    HDU 6045
    HDU 6044
    HDU 6040
    ZUFE 1035 字符宽度编码(字符串)
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9194362.html
Copyright © 2011-2022 走看看