[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 ...
随机推荐
- 一些带dga域名的恶意软件
04/02/2019 06:17下午 6,488,759 f4f242a50ba9efa1593beba6208a2508_PWS.win32.Simda_1250_DGADNS.pcap Simda ...
- The Sum of the k-th Powers(Educational Codeforces Round 7F+拉格朗日插值法)
题目链接 传送门 题面 题意 给你\(n,k\),要你求\(\sum\limits_{i=1}^{n}i^k\)的值. 思路 根据数学知识或者说题目提示可知\(\sum\limits_{i=1}^{n ...
- httprunner学习1-环境与登录接口案例
前言 HttpRunner 是一款面向 HTTP(S) 协议的通用测试框架,只需编写维护一份 YAML/JSON 脚本,即可实现自动化测试. 具有以下优点: 继承 Requests 的全部特性,轻松实 ...
- ML.NET学习笔记 ---- 系列文章
机器学习框架ML.NET学习笔记[1]基本概念与系列文章目录 机器学习框架ML.NET学习笔记[2]入门之二元分类 机器学习框架ML.NET学习笔记[3]文本特征分析 机器学习框架ML.NET学习笔记 ...
- springboot无法识别配置文件级解决办法
eclipse中右键项目bulid path 之后找到 后点击完成后点击运用 修改完成
- Ranger安装部署 - solr安装
1. 概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检索类库: Solr是以Lucene为基础实现的文本检索应用服务.Solr部署方式有单机方式.多机Master-Slaver方法. ...
- C#编写简单的聊天程序(转)
这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考.文章大体分为四个部分:程序的分析与设计.C#网络编 ...
- MyBatis框架的insert节点-向数据库中插入数据
需求:使用mybatis框架中的insert元素节点向数据库中插入数据 UserMapper.xml UserMapper.java 编写测试方法: @Test public void testAdd ...
- h5自带的日期类型input
在很多页面和web应用中都有输入日期和时间的地方,最典型的是订飞机票,火车票,酒店,批萨等网站. 在HTML5之前,对于这样的页面需求,最常见的方案是用Javascript日期选择组件.这几乎是无可争 ...
- Mac OSX上安装SublimeText 3编译Processing 3.0
1.安装SublimeText 32.使用Preferences - Package Control:Install Package - Processing安装 如果移动了Processing的位置 ...