首页 > 其他 > 详细

314. Binary Tree Vertical Order Traversal

时间:2018-06-18 10:02:43      阅读:147      评论:0      收藏:0      [点我收藏+]

问题描述:

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);
            }
        }
    }
};

 

314. Binary Tree Vertical Order Traversal

原文:https://www.cnblogs.com/yaoyudadudu/p/9194362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!