[LC] 314. Binary Tree Vertical Order Traversal

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

这一题并不难。就是要找到最左边的那个节点有多么的左,最右边那个节点有多么的右。然后以最左边的那个节点作为index 0,然后结果的size就是最右边的节点到最左边的节点的横向距离。先通过dfs去求得上面的左右距离,然后根节点的index是他与最左边的节点的横向距离。譬如examples 1里,3的index就是1,因为最左边的那个节点9和他的横向距离就是只有1。然后再做bfs去把每个节点的值放进对应的index的List里面就好了。给出代码如下:

class Solution {
    public List<List<Integer>> verticalOrder(TreeNode root) {
        int[] minMax = new int[2];
        traverseMinMax(root, minMax, 0);
        int offset = -minMax[0];
        int arrSize = minMax[1] - minMax[0];
        ArrayList<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;

        for (int i = 0; i <= arrSize; i++) {
            result.add(new LinkedList<Integer>());
        }
        
        Queue<TreeNode> nodeQ = new LinkedList<TreeNode>();
        Queue<Integer> indexQ = new LinkedList<Integer>();
        nodeQ.add(root);
        indexQ.add(offset);
        while (!nodeQ.isEmpty()) {
            TreeNode node = nodeQ.poll();
            int idx = indexQ.poll();
            result.get(idx).add(node.val);
            if (node.left != null) {
                indexQ.add(idx - 1);
                nodeQ.add(node.left);
            }
            
            if (node.right != null) {
                indexQ.add(idx + 1);
                nodeQ.add(node.right);
            }
        }
        
        return result;
    }
    
    public void traverseMinMax(TreeNode root, int[] minMax, int current) {
        if (root == null) {
            return;
        }
        
        minMax[0] = Math.min(current, minMax[0]);
        minMax[1] = Math.max(current, minMax[1]);
        
        traverseMinMax(root.left, minMax, current - 1);
        traverseMinMax(root.right, minMax, current + 1);
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值