314.二叉树的垂直遍历

314.二叉树的垂直遍历_第1张图片

 链接:https://www.jiuzhang.com/solutions/binary-tree-vertical-order-traversal/

题解:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: the root of tree
     * @return: the vertical order traversal
     */
    vector> verticalOrder(TreeNode * root) {
        // write your code here
        vector> result;
        if (!root) {
            return result;
        }
        std::map> table;
        queue> que;
        que.push(std::pair(0, root));
        table[0].push_back(root->val);
        while (!que.empty()) {
            auto entry = que.front();
            que.pop();
            if (entry.second->left) {
                que.push(std::pair(entry.first-1, entry.second->left));
                table[entry.first-1].push_back(entry.second->left->val);
            }
            if (entry.second->right) {
                que.push(std::pair(entry.first+1, entry.second->right));
                table[entry.first+1].push_back(entry.second->right->val);
            }
        }
        for (auto entry : table) {
            result.push_back(entry.second);
        }
        return result;
    }
};

你可能感兴趣的:(leetcode)