651 · 二叉树垂直遍历

651 · 二叉树垂直遍历

描述
给定二叉树,返回其节点值的垂直遍历顺序。 (即逐列从上到下)。
如果两个节点在同一行和同一列中,则顺序应 从左到右。

样例
样例1

输入: {3,9,20,#,#,15,7}
输出: [[9],[3,15],[20],[7]]
解释:
3
/
/
9 20
/
/
15 7
样例2

输入: {3,9,8,4,0,1,7}
输出:[[4],[9],[3,0,1],[8],[7]]
解释:
3
/
/
9 8
/\ /
/ /
4 01 7

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of tree
     * @return: the vertical order traversal
     */
    public List<List<Integer>> verticalOrder(TreeNode root) {
        // write your code here
        List<List<Integer>> ans = new ArrayList<>() ;
        if(root == null){
            return null ;
        }
        int col_min = 0 ;
        int col_max = 0 ;
        Map<Integer , List<Integer>> col = new HashMap<>() ;
        Queue<Integer> q1 = new LinkedList<>() ;
        Queue<TreeNode> q2 = new LinkedList<>() ;
        q1.add(0) ;
        q2.add(root) ;
        while(! q1.isEmpty()){
            int c = q1.poll() ;
            TreeNode node = q2.poll() ;
            if(! col.containsKey(c)){
                col.put(c , new ArrayList<Integer>()) ;
            }
            col.get(c).add(node.val) ;
            col_min = Math.min(col_min , c) ;
            col_max = Math.max(col_max , c) ;
            if(node.left != null){
                q1.add(c-1) ;
                q2.add(node.left) ;

            }
            if(node.right != null){
                q1.add(c+1) ;
                q2.add(node.right) ;

            }
            
        }
        for(int i = col_min ; i <= col_max ; i++){
                ans.add(col.get(i)) ;
            }
        return ans ;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、树状显示二叉树: 编写函数displaytree(二叉树的根指针,数据值宽度,屏幕的宽度)输出树的直观示意图。输出的二叉树垂直打印的,同层的节点在同一行上。 问题描述: 假设数据宽度datawidth=2,而屏幕宽度screenwidth为64=26,假设节点的输出位置用 (层号,须打印的空格数)来界定。 第0层:根在(0,32)处输出; 第1层:因为根节点缩进了32个空格,所以下一层的偏移量(offset)为32/2=16=screenwidth/22。即第一层的两个节点的位置为(1,32-offset),(1,32+offset)即(1,16),(1,48)。 第二层:第二层的偏移量offset为screenwidth/23。第二层的四个节点的位置分别是(2,16-offset),(2,16+offset),(2,48-offset),(2,48+offset)即(2,8),(2,24),(2,40),(2,56)。 …… 第i层:第i层的偏移量offset为screenwidth/2i+1。第i层的每个节点的位置是访问第i-1层其双亲节点时确定的。假设其双亲的位置为(i-1,parentpos)。若其第i层的节点是其左孩子,那末左孩子的位置是(i,parentpos-offset),右孩子的位置是(i,parentpos+offset)。 提示:利用二叉树的层次遍算法实现。利用两个队列Q,QI。队列Q中存放节点信息,队列QI中存相应于队列Q中的节点的位置信息,包括层号和需要打印节点值时需要打印的空格数。当节点被加入到Q时,相应的打印信息被存到QI中。二叉树本身采用二叉链表存储。 2、完全二叉树判断 用一个二叉链表存储的二叉树,判断其是否是完全二叉树

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值