当前位置: 首页 > news >正文

剑指offer面试题19 二叉树的镜像

考察点

树的遍历

知识点

题目

分析
我们分析算法题目的思路基本上都是归纳法,即通过举一些普通的例子来推理出算法流程,而画图又是举例子的常用手段,比如针对树或者链表画画图,针对数字类的举一些数字的例子寻找规律,很快就能得到解决问题的方案。这道题目要求树的镜像,只要谈到树我们的思维就往那几个遍历上靠,前序遍历树的过程中交换非叶子结点的左子树和右子树就可以了。

public class BinaryTree {Node root;public BinaryTree() {this.root = null;}public void convertMirror(Node root) {if (root == null) {return;}if (root.leftChild != null && root.rightChild != null) {Node tmp = root.leftChild;root.leftChild = root.rightChild;root.rightChild = tmp;}convertMirror(root.leftChild);convertMirror(root.rightChild);}public void insertTree(int val) {if (this.root == null) {Node root = new Node(val);this.root = root;} else {insertChildTree(this.root,val);}}public void insertChildTree(Node node,int val) {if (node != null && val <= node.val) {if (node.leftChild == null) {node.leftChild = new Node(val);} else {insertChildTree(node.leftChild,val);}}if (node != null && val > node.val) {if (node.rightChild == null) {node.rightChild = new Node(val);} else {insertChildTree(node.rightChild,val);}}}public Node getRoot() {return this.root;}public void prePrint(Node node) {if (node == null) {return;}System.out.print(node.val + " ");prePrint(node.leftChild);prePrint(node.rightChild);}
}
public class Node{int val;Node leftChild;Node rightChild;public Node(int data) {this.val = data;this.leftChild = null;this.rightChild = null;}
}
public class Nineteen {public static void main(String[] args) {BinaryTree binaryTree = new BinaryTree();binaryTree.insertTree(8);binaryTree.insertTree(6);binaryTree.insertTree(10);binaryTree.insertTree(5);binaryTree.insertTree(7);binaryTree.insertTree(9);binaryTree.insertTree(11);binaryTree.prePrint(binaryTree.getRoot());System.out.println();binaryTree.convertMirror(binaryTree.getRoot());binaryTree.prePrint(binaryTree.getRoot());}
}
http://www.lryc.cn/news/306297.html

相关文章:

  • SpringCloud Alibaba 2022之Nacos学习
  • js之数组遍历
  • 极狐GitLab 16.9 重磅发布,快来 pick 你心仪的功能吧~【五】
  • 如何在本地部署密码管理软件bitwarden并结合cpolar实现远程同步
  • DT DAY3 信号和槽
  • Spring、SpringBoot、SpringCloud三者的区别
  • leetcode:46.全排列
  • 基于STM32的宠物箱温度湿度监控系统
  • 《高质量的C/C++编程规范》学习
  • 客户端订阅服务端事件的机制
  • pulsar入门介绍
  • Leetcode 3047. Find the Largest Area of Square Inside Two Rectangles
  • ELK 简介安装
  • Linux 的交换空间(swap)是什么?有什么用?
  • 消息中间件篇之RabbitMQ-消息不丢失
  • MongoDB中的TTL索引:自动过期数据的深入解析与使用方式
  • IPV6地址
  • 解密API关键词搜索(淘宝京东1688)商品列表数据
  • wpf 简单实验 数据更新 列表更新
  • 【Flink精讲】Flink性能调优:内存调优
  • Java 中常用的数据结构类 API
  • JavaScript学习小记(1)基本数据结构(数组,字符串)
  • python opencv实现车牌识别
  • K8S节点GPU虚拟化(vGPU)
  • NLP 使用Word2vec实现文本分类
  • 【Redis学习笔记03】Java客户端
  • 神经网络系列---激活函数
  • python中continue的对比理解
  • Amazon Generative AI | 基于 Amazon 扩散模型原理的代码实践之采样篇
  • [服务器-数据库]MongoDBv7.0.4不支持ipv6访问