JAVA二叉树相关习题5

news/2024/5/20 16:05:11

1. 二叉树前序非递归遍历实现 。

. - 力扣(LeetCode)

递归的实现

public List<TreeNode> preOrder1(TreeNode root){List<TreeNode> ret=new ArrayList<>();if(root == null)return ret;ret.add(root);List<TreeNode> leftTree = preOrder1(root.left);ret.addAll(leftTree);List<TreeNode> rightTree = preOrder1(root.right);ret.addAll(rightTree);return ret;}

与栈相结合

public void preOrderNor(TreeNode root) {if(root == null) return;Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;TreeNode top = null;while (cur != null || !stack.isEmpty()) {while (cur != null) {stack.push(cur);System.out.print(cur.val + " ");cur = cur.left;}top = stack.pop();cur = top.right;}}

2. 二叉树中序非递归遍历实现。

. - 力扣(LeetCode)

3. 二叉树后序非递归遍历实现。

. - 力扣(LeetCode)

4. 检查两颗树是否相同。

. - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {//一个为空一个不为空if((p==null&&q!=null)||(p!=null&&q==null)){return false;}//两个都为空if(p==null&&q==null){return true;}//两个都不为空if(p.val!=q.val){return false;}return isSameTree(p.right, q.right)&&isSameTree(p.left, q.left);}
}

5. 另一颗树的子树。

. - 力扣(LeetCode)

//判断左数和其是否相同

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {if(p == null && q != null || p != null && q == null ) {return false;}//两个都为空呢?if(p == null && q == null) {return true;}//一定是两个引用 都不为空 | 两个都不为空呢?if(p.val != q.val) {return false;}return isSameTree(p.left,q.left) &&isSameTree(p.right,q.right);}public boolean isSubtree(TreeNode root, TreeNode subRoot) {if(root==null){return false;}if(isSameTree(root,subRoot)){return true;}if(isSubtree(root.left,subRoot)){return true;}if(isSubtree(root.right,subRoot)){return true;}return false;}
}

 6.翻转二叉树。

. - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public TreeNode invertTree(TreeNode root) {if(root==null){return null;}TreeNode tmp=root.left;root.left=root.right;root.right=tmp;invertTree(root.left);invertTree(root.right);return root;}
}

 7. 判断一颗二叉树是否是平衡二叉树。

但是上述方式复杂度较高

上述代码速度很慢!!!

 . - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public int getHeight(TreeNode root) {if(root == null)return 0;int leftHeight = getHeight(root.left);int rightHeight = getHeight(root.right);if(leftHeight>=0&&rightHeight>=0&&Math.abs(leftHeight-rightHeight)<=1){return Math.max(leftHeight,rightHeight)+1;}else{return -1;}}public boolean isBalanced(TreeNode root) {if(root==null){return true;}return getHeight(root)>=0;}
}

 8.对称二叉树。

. - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public boolean isSymmetric(TreeNode root) {if(root==null){return true;}return isSymmetricChild(root.left,root.right);}public boolean isSymmetricChild(TreeNode p,TreeNode q){if((p==null&&q!=null)||(p!=null&&q==null)){return false;}if(p==null&&q==null){return true;}if(p.val!=q.val){return false;}return isSymmetricChild(p.left,q.right)&&isSymmetricChild(p.right,q.left);}
}

 9.二叉树的构建及遍历。

二叉树遍历_牛客题霸_牛客网

hasNext、hasNextLine、next、nextLine保姆级详解-CSDN博客

import java.util.Scanner;//从头到尾进行书写
class TreeNode{char val;TreeNode left;TreeNode right;//无参构造TreeNode(){}//有参构造TreeNode(char val){this.val=val;}
}
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {public static void main(String[] args) {Scanner in = new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseString str=in.nextLine();TreeNode root=createTree(str);inOrder(root);}}public static int i=0;public static TreeNode createTree(String str){TreeNode root =null;if(str.charAt(i)!='#'){root=new TreeNode(str.charAt(i));i++;root.left=createTree(str);root.right=createTree(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);}
}

10.二叉树的分层遍历 

. - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public List<List<Integer>> levelOrder(TreeNode root) {List<List<Integer>> ret = new ArrayList<>();if(root == null) {return ret;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {//求一下当前队列的大小  4int size = queue.size();//4List<Integer> tmp = new ArrayList<>();while (size != 0) {// 出队列4次 相当于把 这一层的节点都 出队了TreeNode cur = queue.poll();//System.out.print(cur.val+" ");tmp.add(cur.val);size--;//0if(cur.left != null) {queue.offer(cur.left);}if(cur.right != null) {queue.offer(cur.right);}}ret.add(tmp);}return ret;}
}

 11.给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 。

. - 力扣(LeetCode)

方法一: 

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode(int x) { val = x; }* }*/
class Solution {public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {if(root == null) {return null;}if(root == p || root == q) {return root;}TreeNode leftTree = lowestCommonAncestor(root.left,p,q);TreeNode rightTree = lowestCommonAncestor(root.right,p,q);if(leftTree != null && rightTree != null) {return root;}else if(leftTree != null) {return leftTree;}else {return rightTree;}}
}

 方法二:与栈相结合

/*** 找到root 到 node 之间路径上 的 所有 的 节点 存储到stack中** @param root* @param node* @param stack* @return*/private boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {if(root == null || node == null) {return false;}stack.push(root);if(root == node) {return true;}boolean flg = getPath(root.left,node,stack);if(flg) {return true;}boolean flg2 = getPath(root.right,node,stack);if(flg2) {return true;}stack.pop();return false;}public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {if(root == null) {return null;}Stack<TreeNode> stackP = new Stack<>();Stack<TreeNode> stackQ = new Stack<>();getPath(root,p,stackP);getPath(root,q,stackQ);//对栈的操作int sizeP = stackP.size();int sizeQ = stackQ.size();if(sizeP > sizeQ) {int size = sizeP - sizeQ;while (size != 0) {stackP.pop();size--;}}else {int size = sizeQ - sizeP;while (size != 0) {stackQ.pop();size--;}}//两个栈当中 元素的个数是相同的while (!stackP.isEmpty() && !stackQ.isEmpty()) {if(stackP.peek() .equals(stackQ.peek())) {return stackP.peek();}stackP.pop();stackQ.pop();}return null;}

 12. 根据一棵树的前序遍历与中序遍历构造二叉树。

. - 力扣(LeetCode)

先序遍历确定根,根据中序遍历确定左树和右树

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public int priIndex;public TreeNode buildTree(int[] preorder, int[] inorder) {return buildTreeChild(preorder,inorder,0,inorder.length-1);}private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inbegin,int inend) {//1. 没有左树 或者 没有右树了if(inbegin > inend) {return null;}//2.创建根节点TreeNode root = new TreeNode(preorder[priIndex]);//3.从中序遍历当中 找到根节点所在的下标int rootIndex = findIndex(inorder,inbegin,inend,preorder[priIndex]);if(rootIndex == -1) {return null;}priIndex++;//4. 创建左子树 和  右子树root.left = buildTreeChild(preorder,inorder,inbegin,rootIndex-1);root.right = buildTreeChild(preorder,inorder,rootIndex+1,inend);return root;}private int findIndex(int[] inorder,int inbegin,int inend,int key) {for(int i = inbegin;i <= inend;i++) {if(inorder[i] == key) {return i;}}return -1;}}

 13.根据一棵树的中序遍历与后序遍历构造二叉树

. - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/class Solution {public int postIndex ;public TreeNode buildTree(int[] inorder, int[] postorder) {postIndex = postorder.length-1;return buildTreeChild(postorder,inorder,0,inorder.length-1);}private TreeNode buildTreeChild(int[] postorder,int[] inorder,int inbegin,int inend) {//1. 没有左树 或者 没有右树了if(inbegin > inend) {return null;}//2.创建根节点TreeNode root = new TreeNode(postorder[postIndex]);//3.从中序遍历当中 找到根节点所在的下标int rootIndex = findIndex(inorder,inbegin,inend,postorder[postIndex]);if(rootIndex == -1) {return null;}postIndex--;//4. 创建左子树 和  右子树root.right = buildTreeChild(postorder,inorder,rootIndex+1,inend);root.left = buildTreeChild(postorder,inorder,inbegin,rootIndex-1);return root;}private int findIndex(int[] inorder,int inbegin,int inend,int key) {for(int i = inbegin;i <= inend;i++) {if(inorder[i] == key) {return i;}}return -1;}
}

14.二叉树创建字符串。

. - 力扣(LeetCode)

public String tree2str(TreeNode root) {StringBuilder stringBuilder  = new StringBuilder();tree2strChild(root,stringBuilder);return stringBuilder.toString();}private void tree2strChild(TreeNode t,StringBuilder stringBuilder) {if(t == null) {return;}stringBuilder.append(t.val);if(t.left != null) {stringBuilder.append("(");tree2strChild(t.left,stringBuilder);stringBuilder.append(")");}else {if(t.right == null) {return;}else{stringBuilder.append("()");}}if(t.right != null) {stringBuilder.append("(");tree2strChild(t.right,stringBuilder);stringBuilder.append(")");}else {return;}}public void preOrderNor(TreeNode root) {if(root == null) return;Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;TreeNode top = null;while (cur != null || !stack.isEmpty()) {while (cur != null) {stack.push(cur);System.out.print(cur.val + " ");cur = cur.left;}top = stack.pop();cur = top.right;}}public void inOrderNor(TreeNode root) {if(root == null) return;Stack<TreeNode> stack = new Stack<>();TreeNode cur = root;TreeNode top = null;while (cur != null || !stack.isEmpty()) {while (cur != null) {stack.push(cur);cur = cur.left;}top = stack.pop();System.out.print(top.val + " ");cur = top.right;}}

http://www.mrgr.cn/p/85141313

相关文章

Calendar 366 II for Mac v2.15.5激活版:智能日历管理软件

在繁忙的工作和生活中&#xff0c;如何高效管理日程成为了许多人的难题。Calendar 366 II for Mac&#xff0c;作为一款全方位的日历管理软件&#xff0c;以其独特的功能和优秀的用户体验&#xff0c;成为您的日程好帮手。 Calendar 366 II for Mac支持多种视图模式&#xff0c…

loons2024年05月09日20:04:57

1 1 1 11 1 1 11 1 1 11 1 1 11 1 1 11 1 1 11 1 1 1

远动通讯屏的作用

远动通讯屏的作用 远动通讯屏有时有称为调度数据网柜&#xff0c;远动通讯屏具体干啥作用&#xff1f;远动通讯屏是以计算机为基础的生产过程与调度自动化系统&#xff0c;可以对现场的运行设备进行监视和控制、以实现数据采集、设备测量、参数调节以及各类信号报警等各项功能。…

从零开始!学习绘制3D表情的详细指南

在2020 年的苹果全球开发者大会(WWDC)&#xff0c;苹果发布了新的 macOS 11(又名 Big Sur)。其中在UI视觉方面macOS Big Sur 系统最大的变化就是图标上&#xff0c; Big Sur更新了很多新设计风格的 3D应用图标&#xff0c;3D设计的确可以提升UI整体的视觉氛围&#xff0c;并且现…

邮件的发送

邮件发送和接收的协议 SMTP协议 (Simple Mail Transfer Protocol)属于TCP/IP协议族。 控制信件的中转方式,帮助每台计算机在发送或中转信件时找到下一个目的地。 SMTP服务器是遵循SMTP协议的发送邮件服务器。POP3协议 (Post Office Protocol - Version 3)属于TCP/IP协议族。…

P3842 [TJOI2007] 线段

https://img2024.cnblogs.com/blog/3335712/202405/3335712-20240509201346814-526640377.png洛谷-题目链接 [TJOI2007] 线段 提示 我们选择的路线是(1, 1) (1, 6)(2, 6) (2, 3)(3, 3) (3, 1)(4, 1) (4, 2)(5, 2) (5, 6)(6, 6) (6, 4) (6, 6)不难计算得到,路程的总长度是 24。…

力扣-21. 合并两个有序链表-js实现

/*** Definition for singly-linked list.* function ListNode(val, next) {* this.val (valundefined ? 0 : val)* this.next (nextundefined ? null : next)* }*/ /*** param {ListNode} list1* param {ListNode} list2* return {ListNode}*/ const mergeTwoList…

【linux学习指南】linux 环境搭建

文章目录 &#x1f4dd;前言&#x1f320; 云服务器的选择&#x1f320;阿里云&#x1f320;腾讯云&#x1f320;华为云 &#x1f320;使用 XShell 远程登陆到 Linux&#x1f309;下载 XShell &#x1f320;查看 Linux 主机 ip&#x1f309; XShell 下的复制粘贴&#x1f309; …

2024中国植物资源化妆品创新展在国家植物园成功举办

2024中国植物资源化妆品创新展&#xff08;简称国植美妆展&#xff09;于今年05月06日在北京国家植物园圆满落下帷幕。国植美妆展由中国广告协会化妆品工作委员会与中国抗衰老促进会化妆品产业分会指导&#xff0c;北京华晟德观文化科技发展有限公司主办&#xff0c;于03月30日…

ssh、PAM模块

.ssh/known_hosts 存储ssh指纹 sshd 服务器端 /etc/ssh/sshd_config 服务器端的配置文件 man 5 sshd_config 服务器端的配置文件帮助 echo root:1111|chapasswd 修改密码 openssl rand -base 64 9 随机取9位密码(随机数经过base编码取9位) ssh常用参数: Port 22 #生产建…

敏捷冲刺day2--数字工匠队

这个作业属于哪个课程 软件工程这个作业的要求是什么 项目冲刺这个作业的目标 冲刺日志2站立式会议照片工作困难 有部分知识不知道,要额外学习 昨日完成工作 用户登录前面前端初版 今日计划工作 登录界面前后端处理 项目燃尽图每日总结 陈家谦:继续学习 陆靖:继续努力 代码签…

Android C++ 开发调试 LLDB 工具的使用

文章目录 调试环境准备基础命令Breakpoint CommandsWatchpoint CommandsExamining VariablesEvaluating ExpressionsExamining Thread StateExecutable and Shared Library Query Commands 参考&#xff1a; Android 中在进行 NDK 开发的时候&#xff0c;我们经常需要进行 C 代…

CloudXR:更高效便捷的XR应用交互方案

CloudXR是一种新颖而先进的技术,旨在将虚拟现实和增强现实体验从本地设备转移到云端,主要功能也包括了远程渲染、流媒体传输、低延迟、高带宽和高质量的音视频传输。云化XR可以将高保真度的虚拟现实或增强现实场景实时传输到终端设备上,用户只需通过互联网即可感受到身临其境…

原来spring也可以AI

最近大模型是相当的火&#xff0c;尤其是在自然语言处理&#xff08;NLP&#xff09;、图像识别、语音识别等领域的应用&#xff0c;那对于工程同学来说应该如何接住这波破天的富贵呢&#xff1f; 想啥来啥&#xff0c;前段时间LangChain给我们整了一套钢铁战甲&#xff0c;让…

Kafk设计篇01(设计动机+持久化)

背景 本篇文章基于最新版本&#xff1a;kafka 3.7&#xff0c;其他版本的设计&#xff0c;请参考官网&#xff1a; https://kafka.apache.org/documentation/设计动机 任何组件都有它存在的必要&#xff0c;必然是要解决某一类问题的。我们来看看kafka设计的初衷如何。 kaf…

【Matlab-动画-附源码】3分钟教你用Matlab做一个Lorenz动画

lorenz-x-y-z Lorenz三个维度数据 在科研工作中&#xff0c;经常需要将数据可视化以便更好地理解和传达研究成果。 但大家主要放静态图片&#xff0c;而视频或动画通常比静态图片更具吸引力和表现力。AE, Manim太难学&#xff0c;Matlab就可以用来制作动画。 在这篇博客中&…

Golang | Leetcode Golang题解之第69题x的平方根

题目&#xff1a; 题解&#xff1a; func mySqrt(x int) int {if x 0 {return 0}C, x0 : float64(x), float64(x)for {xi : 0.5 * (x0 C/x0)if math.Abs(x0 - xi) < 1e-7 {break}x0 xi}return int(x0) }

QT5带UI的常用控件

目录 新建工程&#xff0c;Qmainwindow带UI UI设计器 常用控件区 Buttons 按钮 containers 容器 控件属性区域 对象监视区 布局工具区 信号与槽区 简单例子1 放置一个按钮控件&#xff0c;改文本为发送&#xff0c;该按键为Button1&#xff1b; 按钮关联信号和…

手动实现简易版RPC(四)

手动实现简易版RPC(四) 往期内容 手动实现简易版RPC&#xff08;一&#xff09;&#xff1a;RPC简介及系统架构 手动实现简易版RPC&#xff08;二&#xff09;&#xff1a;简单RPC框架实现 手动实现简易版RPC(三)&#xff1a;mock数据生成 前言 接上几篇博客我们实现了最…