[LeetCode] 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:
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 二叉树的垂直遍历的更多相关文章
- [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 ...
- [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 ...
- LeetCode 314. Binary Tree Vertical Order Traversal
原题链接在这里:https://leetcode.com/problems/binary-tree-vertical-order-traversal/ 题目: Given a binary tree, ...
- leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)
题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...
- 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, ...
- 【LeetCode】Binary Tree Level Order Traversal(二叉树的层次遍历)
这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15 ...
- leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历
基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行 ...
- [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, ...
- [LeetCode] Binary Tree Vertical Order Traversal 二叉树的竖直遍历
Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bott ...
随机推荐
- app开发-3
一.Audio 模块实现开启手机摄像头 基于html5 plus http://www.html5plus.org/doc/zh_cn/audio.html 栗子: 自定义: scanQR.HTM ...
- 微信小程序~用户转发 onShareAppMessage
只有定义了此事件处理函数,右上角菜单才会显示“转发”按钮,在用户点击转发按钮的时候会调用,此事件需要return一个Object,包含title和path两个字段,用于自定义转发内容 代码使用onSh ...
- Linux——配置maven
前言 Maven是一个项目管理工具,它包含了一个项目对象模型 (Project Object Model),一组标准集合,一个项目生命周期(Project Lifecycle),一个依赖管理系统(De ...
- MySQL Error:Warning: (1366, "Incorrect string value: '\\xF0\\x9F\\x98\\x82\\xF0\\x9F...' for column 'xxx' at row 2")
bug现象 使用连接数据库的可视化软件插入 emoj 表情数据.生僻字,可以正常插入.(导致我一直以为跟表情没有任何关系,谷歌出来一堆跟修改数据库.表.字段 的编码的结果....)但是一启动程序插入新 ...
- Building a Service Mesh with HAProxy and Consul
转自:https://www.haproxy.com/blog/building-a-service-mesh-with-haproxy-and-consul/ HashiCorp added a s ...
- 16-ESP8266 SDK开发基础入门篇--TCP 服务器 非RTOS运行版,串口透传(串口回调函数处理版)
https://www.cnblogs.com/yangfengwu/p/11105466.html 其实官方给的RTOS的版本就是在原先非RTOS版本上增加的 https://www.cnblogs ...
- [xms]西软xms试算平衡报表-穿透明细报表-增加储值卡卡号列
只能呵呵哒 [xms]西软xms试算平衡报表-穿透明细报表-增加储值卡卡号列 pospay ' and hotelid='${hotelid}'; hhaccount ' and hotelid='$ ...
- pycharm+gitee【代码上传下载】实战(windows详细版)
pycharm+gitee环境搭建好以后应该如何进行代码上传下载操作呢?举几个例子,此文会一直更新 环境:2019社区版pycharm+gitee+git 系统:windows系统 一.代码上传功能 ...
- SDN第六次上机作业
1.实验拓扑 实验拓扑图如下: 搭建代码如下: 创建py脚本文件,并编写代码,如下: class MyTopo(Topo): def __init__(self): # initilaize topo ...
- Spring重定向
1.使用HttpServletResponse的sendRedirect()方法. 示例: @PostMapping("/user/product/id") public void ...