实现二叉树的基本操作与OJ练习

目录

1.二叉树的基本操作

1.1二叉树基本操作完整代码 

 1.2检测value值是否存在

1.3层序遍历

1.4判断一棵树是不是完全二叉树 

 2.OJ练习

2.1平衡二叉树

2.2对称二叉树 

2.3二叉树遍历 


1.二叉树的基本操作

1.1二叉树基本操作完整代码 

public class BinaryTree {static class TreeNode{public char val;public TreeNode left;public TreeNode right;public TreeNode(char val) {this.val = val;}}//使用穷举,实现一棵树public TreeNode creatTree() {TreeNode A = new TreeNode('A');TreeNode B = new TreeNode('B');TreeNode C = new TreeNode('C');TreeNode D = new TreeNode('D');TreeNode E = new TreeNode('E');TreeNode F = new TreeNode('F');TreeNode G = new TreeNode('G');TreeNode H = new TreeNode('H');A.left = B;A.right = C;B.left = D;B.right = E;C.left = F;C.right = G;E.right = H;return A;}// 前序遍历  根 左子树 右子树public void preOrder(TreeNode root) {if (root == null) {return;}System.out.print(root.val + " ");preOrder(root.left);preOrder(root.right);}// 中序遍历 左 根 右public void inOrder(TreeNode root) {if (root == null) {return;}inOrder(root.left);System.out.print(root.val + " ");inOrder(root.right);}// 后序遍历 左 右 根public void postOrder(TreeNode root){if (root == null) {return;}inOrder(root.left);inOrder(root.right);System.out.print(root.val + " ");}// 获取树中节点的个数public int sizeCount;public void size(TreeNode root){if(root == null) {return;}sizeCount++;size(root.left);size((root.right));}//子问题public int  size2(TreeNode root) {if (root == null) {return 0;}return size2(root.left) + size2(root.right) + 1;}// 获取叶子节点的个数public int leafCount;//遍历求解public void getLeafNodeCount(TreeNode root) {if (root == null) {return;}if (root.left == null && root.right == null){leafCount++;}getLeafNodeCount(root.left);getLeafNodeCount(root.right);}// 子问题思路-求叶子结点个数public int getLeafNodeCount2(TreeNode root){if (root == null) {return 0;}if (root.left == null && root.right == null) {return 1;}//左子树的叶子节点+右子树的叶子节点return getLeafNodeCount2(root.left) +getLeafNodeCount2(root.right);}// 获取第K层节点的个数public int getKLevelNodeCount(TreeNode root,int k) {if (root == null) {return 0;}if (k == 1) {return 1;}return getKLevelNodeCount(root.left,k-1) +getKLevelNodeCount(root.right,k-1);}// 获取二叉树的高度public int getHeight(TreeNode root) {if (root == null) {return 0;}int leftHeight = getHeight(root.left);int rightHeight = getHeight(root.right);return Math.max(leftHeight,rightHeight) + 1;}// 检测值为value的元素是否存在public TreeNode find(TreeNode root, int val) {if (root == null) {return null;}if (root.val == val) {return root;}TreeNode leftVal = find(root.left,val);if (leftVal != null) {return leftVal;}TreeNode rightVal =find(root.right,val);if (rightVal != null) {return rightVal;}//左、右子树都没有return null;}//层序遍历public void levelOrder(TreeNode root){if (root == null) {return;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {TreeNode cur = queue.poll();System.out.print(cur.val+" ");if(cur.left != null) {queue.offer(cur.left);}if (cur.right != null) {queue.offer(cur.right);}}}//判断一棵树是不是完全二叉树public boolean isCompleteTree(TreeNode root){if(root == null) {return true;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {TreeNode cur = queue.poll();if (cur != null) {queue.offer(cur.left);queue.offer(cur.right);} else {break;}}//走到这里两种情况 1.队列为空 2.遇到breakwhile (!queue.isEmpty()) {TreeNode cur = queue.peek();if (cur != null) {queue.poll();} else {return false;}}return true;}
}

 1.2检测value值是否存在

题解

1.3层序遍历

题解:

层序遍历:就是从上到下,从左到右,依次遍历。前序、中序、后序本质上都是从上到下。

所以,就是要解决从左到右。

可以引入队列解决(先进先出),如果不是空树,先把根节点放到队列里,此时队列不为空,当该节点出队是,用cur记录,不为空并把该节点的左、右节点放进队列。

1.4判断一棵树是不是完全二叉树 

题解:

也是引入队列解决,当cur不为空把该节点的左、右节点放进队列;否则跳出循环。

在遍历队列,是否都为null.

 2.OJ练习

2.1平衡二叉树

题解:

是不是一颗平衡二叉树,当前根节点的左右子树的高度差的绝对值<=1&&根左子树平衡&&根右子树平衡。

如下代码:就会发现求节点3的高度,把每个节点都求了一遍。 求节点9的高度时,也把每个节点都求了一遍。就会有很高度重复求,maxDepth有N个节点,最坏时间复杂度:N*N=N^2.

    public boolean isBalanced(TreeNode root) {if(root == null) {return true;}int leftHeight = maxDepth(root.left);int rightHeight = maxDepth(root.right);return Math.abs(leftHeight - rightHeight) <= 1 &&isBalanced(root.left)&&isBalanced(root.right);}public int maxDepth(TreeNode root) {if (root == null) {return 0;}int leftHeight = maxDepth(root.left);int rightHeight = maxDepth(root.right);return Math.max(leftHeight, rightHeight) + 1;}

 省略掉重复计算的高度!

    public boolean isBalanced2(TreeNode root) {if(root == null) {return true;}return maxDepth(root) >= 0;}public int maxDepth2(TreeNode root) {if (root == null) {return 0;}int leftHeight = maxDepth2(root.left);if(leftHeight < 0) {return -1;}int rightHeight = maxDepth2(root.right);if(leftHeight >= 0 && rightHeight >= 0&& Math.abs(leftHeight - rightHeight) <= 1){return Math.max(leftHeight,rightHeight) + 1;} else {return -1;}}

2.2对称二叉树 

     题目描述:给你一个二叉树的根节点 root , 检查它是否轴对称。 

题解:

    public boolean isSymmetric(TreeNode root) {if(root == null) {return true;}return isSameTree2(root.left,root.right);}public boolean isSameTree2(TreeNode lefTree,TreeNode rightTree){if(lefTree == null && rightTree != null || lefTree != null && rightTree == null) {return false;}if(lefTree == null && rightTree == null) {return true;}if(lefTree.val != rightTree.val) {return false;}return isSameTree2(lefTree.left,rightTree.right)&&isSameTree2(lefTree.right,rightTree.left);}

2.3二叉树遍历 

题目描述:编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

题解: 

  遍历这个字符串,根据前序遍历的方式,创建二叉树

   class TreeNode {char val;TreeNode left;TreeNode right;public TreeNode(char val) {this.val = val;}}// 注意类名必须为 Main, 不要有任何 package xxx 信息public class Main {public static int i = 0;public static void main(String[] args) {Scanner in = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseString str = in.nextLine();TreeNode root = creatTree(str);inOrder(root);}}public static TreeNode creatTree(String str) {//1.遍历字符串//2.创建二叉树TreeNode root = null;if(str.charAt(i)!= '#') {root = new TreeNode(str.charAt(i));i++;root.left = creatTree(str);root.right = creatTree(str);} else{i++;}//返回根节点return root;}public static void inOrder(TreeNode root) {if(root == null) {return;}inOrder(root.left);System.out.print(root.val+" ");inOrder(root.right);}}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/309476.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

UDP信号多个电脑的信息传输测试、配置指南

最近要做一个东西&#xff0c;关于一个软件上得到的信号&#xff0c;如何通过连接的局域网&#xff0c;将数据传输出去。我没做过相关的东西&#xff0c;但是我想应该和软件连接数据库的过程大致是差不多的&#xff0c;就一个ip和一个端口号啥的。 一.问题思路 多个设备同时连…

Linux系统下隧道代理HTTP

在Linux系统下配置隧道代理HTTP是一个涉及网络技术的话题&#xff0c;主要目的是在客户端和服务器之间建立一个安全的通信通道。下面将详细解释如何进行配置。 一、了解基本概念 在开始之前&#xff0c;需要了解几个关键概念&#xff1a;代理服务器、隧道代理和HTTP协议。代理…

【docker实战】01 Linux上docker的安装

Docker CE是免费的Docker产品的新名称&#xff0c;Docker CE包含了完整的Docker平台&#xff0c;非常适合开发人员和运维团队构建容器APP。 Ubuntu 14.04/16.04&#xff08;使用 apt-get 进行安装&#xff09; # step 1: 安装必要的一些系统工具 sudo apt-get update sudo ap…

冒泡排序--------(C每日一题)

冒泡排序&#xff1a; 每次将相邻的两个数比较,将小的调到前头--升序 冒泡排序一个结论&#xff1a; n个数要进行n-1轮比较&#xff0c;第j轮要进行n-j次两两比较 循环体代码&#xff1a; int main() {int i, j,n,a[10],t;//n是几个数比较for(j1;j<n-1;j)//控制轮次for…

linux下docker搭建mysql8

1&#xff1a;环境信息 centos 7,mysql8 安装docker环境 2.创建mysql容器 2.1 拉取镜像 docker pull mysql:8.0.23 2.2 查询镜像拉取成功 docker images 2.3 创建挂载的目录文件 mkdir /usr/mysql8/conf mkdir /usr/mysql8/data ##给data文件赋予操作权限 chmod 777 /…

Flood Fill算法总结

算法思想 从一个起点开始&#xff0c;每一次随机选择一个新加进来的格子&#xff0c;看一下它周围能否扩展新的格子。如果能扩展&#xff0c;那么就扩展进来&#xff0c;直到不能扩展新的格子为止。当然需要判重&#xff0c;同样一个格子只能覆盖一次&#xff0c;这样能够保证时…

HTML---JavaScript基础

文章目录 前言一、pandas是什么&#xff1f;二、使用步骤 1.引入库2.读入数据总结 本章目标 掌握JavaScript的组成掌握JavaScript的基本语法会定义和使用函数会使用工具进行代码调试 一.JavaScript基础 概述 JavaScript是一种基于对象和事件驱动的脚本语言&#xff0c;用于在…

前端优化 - 防抖和节流

&#x1f4e2; 鸿蒙专栏&#xff1a;想学鸿蒙的&#xff0c;冲 &#x1f4e2; C语言专栏&#xff1a;想学C语言的&#xff0c;冲 &#x1f4e2; VUE专栏&#xff1a;想学VUE的&#xff0c;冲这里 &#x1f4e2; CSS专栏&#xff1a;想学CSS的&#xff0c;冲这里 &#x1f4…

flutter打包后的msix安装程序提示:应用安装失败,错误消息: 已阻止程序包 com.flutter.XXXXX 的部署等解决办法

使用dart的依赖msix打包后的程序&#xff0c;提示&#xff1a; 应用安装失败&#xff0c;错误消息: 已阻止程序包 com.flutter.flutterapp_1.0.0.0_x64__fxkeb4dgdm144 的部署&#xff0c;因为提供的程序包具有与已安装的程序包相同的标识&#xff0c;但内容不相同。请提高要安…

数据的复制

基本概念 数据的复制指的是通过网络链接的多台机器保留相同的副本 为什么要进行数据的复制 使得用户和数据在地理上比较接近&#xff0c;因为大数据要求我们将计算安排在数据存放的位置和我们基本的内存模型不是很一样 &#xff0c;比如磁盘调入内存之类的。即使系统的一部分…

C语言经典算法【每日一练】20

题目&#xff1a;有一个已经排好序的数组。现输入一个数&#xff0c;要求按原来的规律将它插入数组中。 1、先排序 2、插入 #include <stdio.h>// 主函数 void main() {int i,j,p,q,s,n,a[11]{127,3,6,28,54,68,87,105,162,18};//排序&#xff08;选择排序&#xff09…

【Git】Git的基本操作

前言 Git是当前最主流的版本管理器&#xff0c;它可以控制电脑上的所有格式的文件。 它对于开发人员&#xff0c;可以管理项目中的源代码文档。&#xff08;可以记录不同提交的修改细节&#xff0c;并且任意跳转版本&#xff09; 本篇博客基于最近对Git的学习&#xff0c;简单介…