DAY 69 LeetCode学习笔记

662. 二叉树最大宽度

前言

昨天给忙忘了,树的最大深度,广度和深度都利用了depth和pos,最左边pos2,右边pos2+1.

题目

官方题目

源码

在这里插入图片描述

/**
 * 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 {
    int ans;
    Map<Integer,Integer> leftMap;
    public int widthOfBinaryTree(TreeNode root) {
        // ====方法1,广度========
        // Queue<Node> queue=new LinkedList<>();
        // queue.add(new Node(root,0,0));
        // int curDepth=0,left=0,ans=0;
        // while(!queue.isEmpty()){
        //     Node cur=queue.poll();
        //     if(cur.node!=null){
        //         queue.add(new Node(cur.node.left,cur.depth+1,cur.pos*2));
        //         queue.add(new Node(cur.node.right,cur.depth+1,cur.pos*2+1));
        //         if(curDepth!=cur.depth){
        //             curDepth=cur.depth;
        //             left=cur.pos;
        //         }
        //         ans=Math.max(ans,cur.pos-left+1);
        //     }

        // }
        // return ans;
        // ====方法1,广度========


        // ========方法2,深度====
        ans=0;
        leftMap=new HashMap();
        dfs(root,0,0);
        return ans;
    }
    public void dfs(TreeNode node, int depth,int pos){
        if(node==null){
            return;
        }
        // java8后的特性,key中的value不存在时直接创建
        leftMap.computeIfAbsent(depth,x->pos);
        ans=Math.max(ans,pos-leftMap.get(depth)+1);
        dfs(node.left,depth+1,2*pos);
        dfs(node.right,depth+1,2*pos+1);
    }
    //======== 方法2=======
}
// ========方法1====== 
// class Node{
//     TreeNode node;
//     int pos,depth;
//     Node(TreeNode n,int d,int p){
//         node=n;
//         depth=d;
//         pos=p;
//     }
// }
// ========方法1======
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值