牛客题目链接
1. 题目考点
根据先序和中序遍历数组重建二叉树 二叉树层次遍历过程中每层最后一个节点 ArrayList 转换成 int[]
2. 考点解析
递归重建二叉树,每次递归前划分对应的先序和中序数组
public TreeNode reBuild ( int [ ] xianxu, int [ ] zhongxu) {
if ( xianxu. length == 0 || zhongxu. length == 0 ) return null;
TreeNode root = new TreeNode ( xianxu[ 0 ] ) ;
int i = getIndex ( zhongxu, xianxu[ 0 ] ) ;
int [ ] xianxul = Arrays. copyOfRange ( xianxu, 1 , i + 1 ) ;
int [ ] xianxur = Arrays. copyOfRange ( xianxu, i + 1 , xianxu. length) ;
int [ ] zhongxul = Arrays. copyOfRange ( zhongxu, 0 , i) ;
int [ ] zhongxur = Arrays. copyOfRange ( zhongxu, i + 1 , zhongxu. length) ;
root. left = reBuild ( xianxul, zhongxul) ;
root. right = reBuild ( xianxur, zhongxur) ;
return root;
}
二叉树层次遍历获取每层最后一个节点
public void bfs ( TreeNode root, ArrayList< Integer> list) {
if ( root == null) return ;
Queue< TreeNode> queue = new LinkedList < > ( ) ;
queue. offer ( root) ;
int curLevelCount = 1 , nextLevelCount = 0 ;
while ( ! queue. isEmpty ( ) ) {
root = queue. poll ( ) ;
curLevelCount -= 1 ;
if ( root. left != null) {
queue. offer ( root. left) ;
nextLevelCount += 1 ;
}
if ( root. right != null) {
queue. offer ( root. right) ;
nextLevelCount += 1 ;
}
if ( curLevelCount == 0 ) {
list. add ( root. val) ;
curLevelCount = nextLevelCount;
nextLevelCount = 0 ;
}
}
}
ArrayList 转化 int[],拆箱mapToInt()
用 stream 流
ArrayList< Integer> list = new ArrayList < > ( ) ;
int [ ] a = list. stream ( ) . mapToInt ( k- > k) . toArray ( ) ;
int[] 转 ArrayList,装箱boxed()
用 stream 流
int [ ] a = new int [ ] { 1 , 3 , 4 } ;
List< Integer> list = Arrays. stream ( a) . boxed ( ) . collect ( Collectors. toList ( ) ) ;
3. 参考链接
int[] 转 ArrayList 牛客题目解析