剑指Offer之Java算法习题精讲二叉树与N叉树
作者:明天一定. 时间:2023-04-22 00:20:42
题目一
解法
/**
* 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 {
StringBuffer sb = new StringBuffer();
List<String> list = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
method(root);
return list;
}
public void method(TreeNode root){
if(root==null) return;
int t = sb.length();
sb.append(root.val);
if(root.left==null&&root.right==null){
list.add(sb.toString());
}
sb.append("->");
method(root.left);
method(root.right);
sb.delete(t, sb.length());
}
}
题目二
解法
/**
* 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 {
int ans = 0;
public int sumOfLeftLeaves(TreeNode root) {
method(root,false);
return ans;
}
public void method(TreeNode root,boolean flag){
if(root==null) return;
if(root.left==null&&root.right==null&&flag){
ans+=root.val;
return;
}
method(root.left,true);
method(root.right,false);
}
}
题目三
解法
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
if(root==null){
return 0;
}
int maxChildDepth = 0;
for(int i = 0;i<root.children.size();i++){
int childDepth = maxDepth(root.children.get(i));
maxChildDepth = Math.max(maxChildDepth, childDepth);
}
return maxChildDepth+1;
}
}
来源:https://blog.csdn.net/wai_58934/article/details/123560260
标签:Java,二叉树,N叉树
0
投稿
猜你喜欢
Flutter开发Mac桌面应用实现自动提取生成视频字幕文件
2023-05-11 05:25:58
C#中Linq的去重方式Distinct详解
2022-01-23 03:53:36
python调用java的jar包方法
2023-06-23 21:54:24
浅谈spring方法级参数校验(@Validated)
2021-06-25 00:43:25
一起来学习Java IO的转化流
2023-11-26 20:38:30
C#使用读写锁三行代码简单解决多线程并发的问题
2023-08-16 12:15:39
Java深度复制功能与用法实例分析
2023-07-05 11:23:17
C#实现HSL颜色值转换为RGB的方法
2022-02-21 09:56:11
Java读写文件,在文件中搜索内容,并输出含有该内容的所有行方式
2022-12-14 18:23:58
springcloud整合seata的实现代码
2022-04-26 23:49:49
Android中Intent传递对象的两种方法Serializable,Parcelable
2021-05-24 03:11:58
详解spring mvc中url-pattern的写法
2023-11-11 07:30:58
java request.getHeader("user-agent")获取浏览器信息的方法
2022-05-28 01:04:26
用 FieldMask 提高 C# gRpc 的服务性能
2023-05-03 19:19:05
Java五种方式实现多线程循环打印问题
2023-03-07 20:34:12
IDEA设置生成带注释的getter和setter的图文教程
2023-06-28 00:49:36
多线程如何解决for循环效率的问题
2023-12-02 08:31:55
Java集合之Comparable和Comparator接口详解
2022-10-04 06:03:44
Nginx启用压缩及开启gzip 压缩的方法
2021-09-20 21:19:25
C# GDI+实现时钟表盘
2023-06-20 07:11:32