Python 官方文档:入门教程 => 点击学习
题目一 解法 class Solution { public int maxDepth(Treenode root) { return m
解法
class Solution {
public int maxDepth(Treenode root) {
return method(root);
}
int method(TreeNode root){
if(root==null){
return 0;
}
int l = method(root.left);
int r = method(root.right);
return Math.max(l, r) + 1;
}
}
解法
class Solution {
int ans = 0;
public int diameterOfBinaryTree(TreeNode root) {
method(root);
return ans;
}
public int method(TreeNode root){
if(root==null){
return 0;
}
int l = method(root.left);
int r = method(root.right);
ans = Math.max(ans,l+r);
return Math.max(l,r)+1;
}
}
解法
class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
if(root.left==null&&root.right==null) return 1;
int min = Integer.MAX_VALUE;
if(root.left!=null){
min = Math.min(min,minDepth(root.left));
}
if(root.right!=null){
min = Math.min(min,minDepth(root.right));
}
return min+1;
}
}
解法
class Solution {
List<Integer> list = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
method(root);
return list;
}
public void method(TreeNode root){
if(root==null){
return;
}
// 前序
list.add(root.val);
method(root.left);
// 中序
method(root.right);
// 后序
}
}
到此这篇关于剑指Offer之Java算法习题精讲二叉树专题篇下的文章就介绍到这了,更多相关Java 二叉树内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 剑指Offer之Java算法习题精讲二叉树专题篇下
本文链接: https://www.lsjlt.com/news/142975.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0