当前位置:网站首页>字节跳动面试题之镜像二叉树2020
字节跳动面试题之镜像二叉树2020
2022-08-09 06:29:00 【史上最强的弟子】
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
实例:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
解题思路是树的广度优先遍历,这里还有一个数据交换问题,是数组数据块数据交换问题的延伸题目,有兴趣的可以去看看左神的 A B A BA 交换问题。
import java.util.ArrayList;
import java.util.List;
public class test7 {
public TreeNode mirrorTree(TreeNode root) {
if(root == null){
return root;
}
List<TreeNode> list = new ArrayList<>();
list.add(root);
while (list.size()>0){
List<TreeNode> newList = new ArrayList<>();
for(int i = 0;i<list.size();i++) {
TreeNode treeNode = list.get(i);
TreeNode node3 = treeNode.left;
treeNode.left = treeNode.right;
treeNode.right = node3;
if(treeNode.left!=null){
newList.add(treeNode.left);
}
if(treeNode.right!=null){
newList.add(treeNode.right);
}
}
list = newList;
}
return root;
}
public static void main(String[] args) {
test7 test7 = new test7();
TreeNode treeNode1 = new TreeNode(4);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(7);
TreeNode treeNode4 = new TreeNode(1);
TreeNode treeNode5 = new TreeNode(3);
TreeNode treeNode6 = new TreeNode(6);
TreeNode treeNode7 = new TreeNode(9);
treeNode1.left =treeNode2;
treeNode1.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
treeNode3.left = treeNode6;
treeNode3.right = treeNode7;
TreeNode treeNode = test7.mirrorTree(treeNode1);
System.out.println(treeNode);
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x) { val = x; }
}
输出结果:
边栏推荐
猜你喜欢
输入框最前面添加放大镜&&background-image和background-color冲突问题
The solution that does not work and does not take effect after VScode installs ESlint
中英文说明书丨TRC 交替醇(Catalogue NumberA575760)
[GO], arrays and slices
【Feel】Unity Feel插件中,Camera无法正确显示CameraShake
Introduction to AIOT
Invalid argument(s) appears when redis runs lua script
How to find package information and pin definitions for NXP S32K1xx series microcontrollers
[MySQL]二、进程的关系、MySQL密码破解、建表和建库相关命令
idea中PlantUML插件使用
随机推荐
AD的library中 库文件后缀有.intlib .schlib .pcblib 的区别
关于如何查找NXP S32K1xx系列单片机的封装信息和引脚定义
治疗消化性溃疡—Toronto Research Chemicals 甘氨酸铝
e-learning summary
GNNExplainer applied to node classification task
Altium designer软件常用最全封装库,包含原理图库、PCB库和3D模型库
简单使用Lambda表达式
After the VB.net program is closed, the background is still connected to SQL
[GO]、数组与切片
报错:FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS重大开销和将disab补充道
VS2019常用快捷键
2022-08-08: Given an array arr, it represents the height of the missiles that will appear in order from morning to night.When the cannon shoots missiles, once the cannon is set to shoot at a certain h
Web APIs BOM- 操作浏览器:本地存储
[MySQL]二、进程的关系、MySQL密码破解、建表和建库相关命令
[R language] Normalize and organize files into folders of various file types
DDD 领域驱动设计
kubernetes security
单例模式
阿里巴巴官方技术号
IQ Products巨细胞病毒CMV感染检测试剂盒的特征和应用