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

Given binary tree [3,9,20,4,5,2,7],

    _3_
/ \
9 20
/ \ / \
4 5 2 7

return its vertical order traversal as:

[
[4],
[9],
[3,5,2],
[20],
[7]
]

二叉树的垂直遍历。

解法:如果一个node的column是 i,那么它的左子树column就是i - 1,右子树column就是i + 1。建立一个TreeColumnNode,包含一个TreeNode,以及一个column value,然后用level order traversal进行计算,并用一个HashMap保存column value以及相同value的点。也要设置一个min column value和一个max column value,方便最后按照从小到大顺序获取hashmap里的值输出。

Java:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private class TreeColumnNode{
public TreeNode treeNode;
int col;
public TreeColumnNode(TreeNode node, int col) {
this.treeNode = node;
this.col = col;
}
} public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) {
return res;
}
Queue<TreeColumnNode> queue = new LinkedList<>();
Map<Integer, List<Integer>> map = new HashMap<>();
queue.offer(new TreeColumnNode(root, 0));
int curLevel = 1;
int nextLevel = 0;
int min = 0;
int max = 0; while(!queue.isEmpty()) {
TreeColumnNode node = queue.poll();
if(map.containsKey(node.col)) {
map.get(node.col).add(node.treeNode.val);
} else {
map.put(node.col, new ArrayList<Integer>(Arrays.asList(node.treeNode.val)));
}
curLevel--; if(node.treeNode.left != null) {
queue.offer(new TreeColumnNode(node.treeNode.left, node.col - 1));
nextLevel++;
min = Math.min(node.col - 1, min);
}
if(node.treeNode.right != null) {
queue.offer(new TreeColumnNode(node.treeNode.right, node.col + 1));
nextLevel++;
max = Math.max(node.col + 1, max);
}
if(curLevel == 0) {
curLevel = nextLevel;
nextLevel = 0;
}
} for(int i = min; i <= max; i++) {
res.add(map.get(i));
} return res;
}
}

Java:

class Solution {
public List<List<Integer>> verticalOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root==null)
return result; // level and list
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>(); LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
LinkedList<Integer> level = new LinkedList<Integer>(); queue.offer(root);
level.offer(0); int minLevel=0;
int maxLevel=0; while(!queue.isEmpty()){
TreeNode p = queue.poll();
int l = level.poll(); //track min and max levels
minLevel=Math.min(minLevel, l);
maxLevel=Math.max(maxLevel, l); if(map.containsKey(l)){
map.get(l).add(p.val);
}else{
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(p.val);
map.put(l, list);
} if(p.left!=null){
queue.offer(p.left);
level.offer(l-1);
} if(p.right!=null){
queue.offer(p.right);
level.offer(l+1);
}
} for(int i=minLevel; i<=maxLevel; i++){
if(map.containsKey(i)){
result.add(map.get(i));
}
} return result;
}
}

Python:  BFS + hash solution.

class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
cols = collections.defaultdict(list)
queue = [(root, 0)]
for node, i in queue:
if node:
cols[i].append(node.val)
queue += (node.left, i - 1), (node.right, i + 1)
return [cols[i] for i in xrange(min(cols.keys()), max(cols.keys()) + 1)] \
if cols else []

C++:

class Solution {
public:
vector<vector<int>> verticalOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
map<int, vector<int>> m;
queue<pair<int, TreeNode*>> q;
q.push({0, root});
while (!q.empty()) {
auto a = q.front(); q.pop();
m[a.first].push_back(a.second->val);
if (a.second->left) q.push({a.first - 1, a.second->left});
if (a.second->right) q.push({a.first + 1, a.second->right});
}
for (auto a : m) {
res.push_back(a.second);
}
return res;
}
};
/**
* 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) {
unordered_map<int, vector<int>> cols;
vector<pair<TreeNode *, int>> queue{{root, 0}};
for (int i = 0; i < queue.size(); ++i) {
TreeNode *node;
int j;
tie(node, j) = queue[i];
if (node) {
cols[j].emplace_back(node->val);
queue.push_back({node->left, j - 1});
queue.push_back({node->right, j + 1});
}
}
int min_idx = numeric_limits<int>::max(),
max_idx = numeric_limits<int>::min();
for (const auto& kvp : cols) {
min_idx = min(min_idx, kvp.first);
max_idx = max(max_idx, kvp.first);
}
vector<vector<int>> res;
for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) {
res.emplace_back(move(cols[i]));
}
return res;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 314. Binary Tree Vertical Order Traversal 二叉树的垂直遍历的更多相关文章

  1. [LeetCode] 314. Binary Tree Vertical Order Traversal 二叉树的竖直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

  2. [leetcode]314. Binary Tree Vertical Order Traversal二叉树垂直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

  3. LeetCode 314. Binary Tree Vertical Order Traversal

    原题链接在这里:https://leetcode.com/problems/binary-tree-vertical-order-traversal/ 题目: Given a binary tree, ...

  4. leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)

    题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...

  5. LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历 C++

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  6. 【LeetCode】Binary Tree Level Order Traversal(二叉树的层次遍历)

    这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15 ...

  7. leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历

    基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行 ...

  8. [LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  9. [LeetCode] Binary Tree Vertical Order Traversal 二叉树的竖直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...

随机推荐

  1. Python练习题——用列表的方法输出杨辉三角

    def main(): num = int(input('请输入行数: ')) yh = [[]] * num #创建num行空列表 for row in range(len(yh)): #遍历每一行 ...

  2. CodeForces - 24D :Broken robot (DP+三对角矩阵高斯消元 随机)

    pro:给定N*M的矩阵,以及初始玩家位置. 规定玩家每次会等概率的向左走,向右走,向下走,原地不动,问走到最后一行的期望.保留4位小数. sol:可以列出方程,高斯消元即可,发现是三角矩阵,O(N* ...

  3. Hibernate缓存简介和对比、一级缓存、二级缓存详解

    一.hibernate缓存简介 缓存的范围分为3类:  1.事务范围(单Session即一级缓存)     事务范围的缓存只能被当前事务访问,每个事务都有各自的缓存,缓存内的数据通常采用相互关联的对象 ...

  4. docker-compose部署gitlab

    一.安装docker-compose步骤可参考本博客其他文章 二.这里的ssl证书是使用letsencrypt生成,可参考文档https://my.oschina.net/u/3042999/blog ...

  5. Pycharm中打开Terminal方式

    点击剪头的图标就可以在左侧出现Terminal

  6. sql语句的面试题

    中科软的面试题:http://www.mayiwenku.com/p-5888480.html 中科软的面试题:https://blog.csdn.net/woolceo/article/detail ...

  7. 一. python 安装

    1. 下载安装包 1 2 3 https://www.python.org/ftp/python/2.7.14/python-2.7.14.amd64.msi    # 2.7安装包   https: ...

  8. OLED液晶屏幕(3)串口读取文字并分割

    https://blog.csdn.net/iracer/article/details/50334041 String comdata = ""; void setup() { ...

  9. LeetCode 1099. Two Sum Less Than K

    原题链接在这里:https://leetcode.com/problems/two-sum-less-than-k/ 题目: Given an array A of integers and inte ...

  10. 2019.12.09 Random 随机数类

    //导包import java.util.Random;class Demo02 { public static void main(String[] args) { //创建Random对象 Ran ...