Tree——No.987 Vertical Order Traversal of a Binary Tree

本文介绍了一种二叉树的纵向遍历算法,通过记录每个节点的位置信息并进行排序,实现了从左到右按列返回节点值的功能。具体方法包括构建位置信息类并实现比较方法,以及遍历树来收集所有节点的位置。

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

Problem:

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.

Explanation:

以一棵树的根节点为(0,0),左孩子为(-1,-1),右孩子为(1,-1),依次类推,纵向遍历树,即横坐标相同的为一组。

My Thinking:

My Solution:

Optimum Thinking:

使用一个location类保存结点位置信息

Optimum Solution:

class Solution {
    List<Location> locations=new ArrayList();
    public List<List<Integer>> verticalTraversal(TreeNode root) {
        traversal(root,0,0);//构建位置信息列表
        Collections.sort(locations);//对列表按照自定义排序方式进行排序
        
        List<List<Integer>> result=new ArrayList<>();
        result.add(new ArrayList<Integer>());
        int prev = locations.get(0).x;
        for (Location loc: locations) {
            if (loc.x != prev) {
                prev = loc.x;
                result.add(new ArrayList<Integer>());
            }
            result.get(result.size() - 1).add(loc.val);
        }
        return result;
    }
    
    public void traversal(TreeNode root,int x,int y){//为每个结点构建一个位置信息
        if(root==null)
            return;
        locations.add(new Location(x,y,root.val));
        traversal(root.left,x-1,y+1);
        traversal(root.right,x+1,y+1);
    }


}
class Location implements Comparable<Location>{//位置信息类,重写compareto方法用于比较
    int x, y, val;
    Location(int x, int y, int val) {
        this.x = x;
        this.y = y;
        this.val = val;
    }

    @Override
    public int compareTo(Location that) {
        if (this.x != that.x)
            return Integer.compare(this.x, that.x);
        else if (this.y != that.y)
            return Integer.compare(this.y, that.y);
        else
            return Integer.compare(this.val, that.val);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值