987. Vertical Order Traversal of a Binary Tree

本文介绍了一种使用TreeMap和优先队列解决LeetCode上二叉树垂直遍历问题的方法。通过递归深度优先搜索,将节点位置信息映射到TreeMap中,并利用优先队列确保同一位置上的节点按值从小到大排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

Given a binary tree, return the vertical order traversal of its nodes values.

For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).

Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report the values of the nodes in order from top to bottom (decreasing Y coordinates).

If two nodes have the same position, then the value of the node that is reported first is the value that is smaller.

Return an list of non-empty reports in order of X coordinate. Every report will have a list of values of nodes.
在这里插入图片描述在这里插入图片描述在这里插入图片描述

题目链接

https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/

方法思路

TreeMap 是一个有序的key-value集合,它是通过红黑树实现的。
TreeMap 继承于AbstractMap,所以它是一个Map,即一个key-value集合。

优先队列的作用是能保证每次取出的元素都是队列中权值最小的(Java的优先队列每次取最小元素,C++的优先队列每次取最大元素)。
Java中PriorityQueue通过二叉小顶堆实现,可以用一棵完全二叉树表示。

    //Runtime: 3 ms, faster than 98.30% 
    //Memory Usage: 37.5 MB, less than 22.46%
    public List<List<Integer>> verticalTraversal(TreeNode root) {
        TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map = new TreeMap<>();
        dfs(root, 0, 0, map);
        List<List<Integer>> list = new ArrayList<>();
        for (TreeMap<Integer, PriorityQueue<Integer>> ys : map.values()) {
            list.add(new ArrayList<>());
            for (PriorityQueue<Integer> nodes : ys.values()) {
                while (!nodes.isEmpty()) {
                    list.get(list.size() - 1).add(nodes.poll());
                }
            }
        }
        return list;
    }
    private void dfs(TreeNode root, int x, int y, TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map) {
        if (root == null) {
            return;
        }
        if (!map.containsKey(x)) {
            map.put(x, new TreeMap<>());
        }
        if (!map.get(x).containsKey(y)) {
            map.get(x).put(y, new PriorityQueue<>());
        }
        map.get(x).get(y).offer(root.val);
        dfs(root.left, x - 1, y + 1, map);
        dfs(root.right, x + 1, y + 1, map);
    }
}
To convert the given array to a complete BST, we need to perform the following steps: 1. Sort the array in ascending order 2. Construct a complete binary tree using the sorted array 3. Perform inorder traversal of the binary tree and store the elements in the original array in the same order as the traversal Here's the implementation of the to_bst(lst) function in Python: ```python def to_bst(lst): # Sort the input list lst.sort() # Construct a complete binary tree using the sorted list n = len(lst) if n == 0: return lst root = lst[n // 2] left_subtree = to_bst(lst[:n // 2]) right_subtree = to_bst(lst[n // 2 + 1:]) binary_tree = [root] + left_subtree + right_subtree # Perform inorder traversal of the binary tree and store the elements in the original array inorder_traversal(binary_tree, lst, 0) return lst def inorder_traversal(binary_tree, lst, i): # Perform inorder traversal of the binary tree and store the elements in the original array n = len(binary_tree) if i >= n: return inorder_traversal(binary_tree, lst, 2 * i + 1) lst[i] = binary_tree[i] inorder_traversal(binary_tree, lst, 2 * i + 2) ``` The to_bst(lst) function takes in the input list and returns the same list after converting it to a complete BST. The function first sorts the input list in ascending order. It then constructs a complete binary tree using the sorted list by recursively dividing the list into two halves and setting the middle element as the root of the binary tree. Finally, the function performs an inorder traversal of the binary tree and stores the elements in the original list in the same order as the traversal.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值