二叉树的垂序遍历
leetcode 987. 二叉树的垂序遍历
题目描述
DFS + 优先队列(堆)
代码演示
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
/**
* 优先级队列
*/
static PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> {
//不是同一列时,列小的排前面
if (a[0] != b[0]) {
return a[0] - b[0];
}
//同一列时,高度低的排前面
if (a[1] != b[1]) {
return a[1] - b[1];
}
//按大小排序
return a[2] - b[2];
});
/**
* 垂序遍历
* @param root
* @return
*/
public static List<List<Integer>> verticalTraversal(TreeNode root){
int[] info = {0, 0, root.val};
queue.add(info);
dfs(root,info);
List<List<Integer>> ans = new ArrayList<>();
while (!queue.isEmpty()){
ArrayList<Integer> list = new ArrayList<>();
int[] peek = queue.peek();
//同一列的放到一个数组集合中
while (!queue.isEmpty() && queue.peek()[0] == peek[0]){
list.add(queue.poll()[2]);
}
ans.add(list);
}
return ans;
}
/**
* 递归
* @param root
* @param f
*/
public static void dfs(TreeNode root,int[]f){
if (root.left != null){
int[] lInfo = {f[0] - 1, f[1] + 1, root.left.val};
queue.add(lInfo);
dfs(root.left,lInfo);
}
if (root.right != null){
int[]rInfo = {f[0] + 1,f[1] + 1, root.right.val};
queue.add(rInfo);
dfs(root.right,rInfo);
}
}
}
二叉树专题
leetcode111. 二叉树的最小深度
leetcode814. 二叉树剪枝
leetcode257. 二叉树的所有路径
leetcode863. 二叉树中所有距离为 K 的结点
剑指 Offer 04. 二维数组中的查找