leetcode Maximum Width of Binary Tree

题目描述:

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.




题解:参考leetcode上的代码,有点小收获,记录一下自己的理解

首先我们对树中节点按照数组存储形式标号,根节点标号为1,它的左右节点标号分别为2,3。如果有一个节点标号为n,则其左右节点标号分别为2*n,2*n+1;

然后dfs按先序遍历树中节点,定义两个数组start,end,start用来 记录每层最左节点标号,end用来记录每层最右节点标号。end数组会随着遍历节点的过程不断变化。


代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
class Solution {
   
    public int widthOfBinaryTree(TreeNode root) {
          ArrayList<Integer> start=new ArrayList<>();
          ArrayList<Integer> end=new ArrayList<>();
          return dfs(root,0,1,start,end);
    }
    
    public int dfs(TreeNode root,int level,int order,List<Integer> start,List<Integer> end){
        if(root==null){
            return 0;
        }
        if(start.size()==level){
            start.add(order);
            end.add(order);
        }
        end.set(level,order);
        int cur=end.get(level)-start.get(level)+1;
        int left=dfs(root.left,level+1,2*order,start,end);
        int right=dfs(root.right,level+1,2*order+1,start,end);
        return Math.max(cur,Math.max(left,right));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值