【LeetCode】662. Maximum Width of Binary Tree二叉树的最大宽度

662. Maximum Width of Binary Tree二叉树的最大宽度

Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.

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.

It is guaranteed that the answer will in the range of 32-bit signed integer.

取得二叉树的最大宽度,包含子节点的null值。

思路:

设根节点在数组的下标为x,那么它的两个子结点下标为2x和2x+1。
用两个数组left[]和right[]分别记录每层最左结点和最右结点的数组下标,那么每层的最大宽度为最右结点的下标减去最左结点的下标+1(right[Level]-left[Level]+1),循环步骤直到到达最深的子节点,也就是深度优先搜索(DFS)。

//init left[] and right[]...
public static int searchMaximumWidth(TreeNode root, int level, int index, List<Integer> left, List<Integer> right){
	//到达null值也就是该结点没有子结点了,不再递归直接返回
	if(root == null){
		return 0;
	}
    
    //第一次到达新的一层才保存最左结点的下标,否则更新最右结点下标   
    if(left.size() == level){
        left.add(index); 
        right.add(index);
    }else{
    	right.set(level, index);
    }
	 
	//当前宽度
	int currentWidth = right[level] - left[level] + 1;
	//递归左子结点
	int left = dfs(root.leftTree, level + 1, 2*index, left, right);
	//递归右子结点
    int right = dfs(root.rightTree, level + 1, 2*index+ 1, left, right);
	
	//取左右子树的最大宽度与当前层宽度比较返回
	return Math.max(currentWidth, Math.max(left,right));
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值