[牛客算法总结]:标题
标签:
二叉树、DFS、先序遍历、中序遍历、递归、队列
题目:
请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图。
如输入[1,2,4,5,3],[4,2,5,1,3]时,通过前序遍历的结果[1,2,4,5,3]和中序遍历的结果[4,2,5,1,3]可重建出以下二叉树:
所以对应的输出为[1,3,5]。
反思:个人思考
所谓右视图,指的是每层的最后一个。二叉树每层,需要使用BFS,使用到队列来解决。
具体过程
重建二叉树看我上一篇博客:重建二叉树
然后再通过BFS输出每层最后一个即可。
用到的知识点:
二叉树、DFS、先序遍历、中序遍历、递归、队列
代码:代码内容
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求二叉树的右视图
* @param xianxu int整型一维数组 先序遍历
* @param zhongxu int整型一维数组 中序遍历
* @return int整型一维数组
*/
List<Integer> arrayList = new ArrayList();
public int getRootIndexInOrder(int[] xianxu, int[] zhongxu) {
for (int i = 0; i < zhongxu.length; i++) {
if (xianxu[0] == zhongxu[i]) return i;
}
return -1;
}
public TreeNode getRightTree(int[] xianxu, int[] zhongxu) {
// write code here
if (xianxu == null || xianxu.length == 0) return null;
int preLength = xianxu.length;
int inOrderLength = zhongxu.length;
// 创建树根
TreeNode root = new TreeNode(xianxu[0]);
int index = getRootIndexInOrder(xianxu, zhongxu);
// 先序:[1,2,4,5,3]
// 中序:[4,2,5,1,3]
root.left = getRightTree(
Arrays.copyOfRange(xianxu, 1, index + 1),
Arrays.copyOfRange(zhongxu, 0, index)
);
root.right = getRightTree(
Arrays.copyOfRange(xianxu, index + 1, preLength),
Arrays.copyOfRange(zhongxu, index + 1, inOrderLength)
);
return root;
}
public void getRightViewList(TreeNode root) {
if (root == null) return;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- != 0) {
TreeNode poll = queue.poll();
if (poll.left != null) {
queue.add(poll.left);
}
if (poll.right != null) {
queue.add(poll.right);
}
if (size == 0) arrayList.add(poll.val);
}
}
}
public int[] solve (int[] xianxu, int[] zhongxu) {
TreeNode root = getRightTree(xianxu, zhongxu);
getRightViewList(root);
return arrayList.stream().mapToInt(Integer::intValue).toArray();
}
}