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));
}