[Leetcode] 314. Binary Tree Vertical Order Traversal 解题报告

来源:互联网 发布:冬天通勤穿 知乎 编辑:程序博客网 时间:2024/06/08 04:55

题目

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]]

思路

这道题目的基本思路是比较明显的,即首先构造一个map,其key值为在竖直方向上的位置,value则是在该位置上的所有结点值。然后在遍历树的过程中填充该map。这道题目的一个坑就是:我开始用了DFS,但是后来发现会导致同一竖直层中元素的顺序不对(例如最后一个例子中的倒数第二行[8,2]用DFS会形成[2,8])。所以正确的解法是采用BFS。

代码

/** * 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) {        if (root == NULL) {            return {};        }        map<int, vector<int>> mp;        vector<vector<int>> ret;        queue<pair<TreeNode*, int>> q;        q.push(make_pair(root, 0));        while(!q.empty()) {            TreeNode* node = q.front().first;            int index = q.front().second;            q.pop();            mp[index].push_back(node->val);            if(node->left) {                q.push(make_pair(node->left, index - 1));            }            if(node->right) {                q.push(make_pair(node->right, index + 1));            }        }        for(auto it = mp.begin(); it != mp.end(); ++it) {            ret.push_back(it->second);        }        return ret;    }};

阅读全文
0 0