有大神能教一下菜菜嘛?求二叉树的最小值节点和最大值节点的距离
看了答案知道了用lca+depth的方式做,但是我很好奇我为什么是wa呜呜呜
package org.example;
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 树的根节点
* @return int整型
*/
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
public void getMaxMin(TreeNode root){
if(root==null){
return ;
}
max =Math.max(max,root.val);
min =Math.min(min,root.val);
getMaxMin(root.left);
getMaxMin(root.right);
}
Map<TreeNode,Integer> mapmin = new HashMap<>();
Map<TreeNode,Integer> mapmax = new HashMap<>();
public boolean getparent(TreeNode root,int target,Map<TreeNode,Integer> map){
if (root==null){
return false;
}
if(root.val==target){
map.put(root,0);
return true;
}
boolean t1 = getparent(root.left,target,map);
boolean t2 = getparent(root.right,target,map);
if (t1){
map.put(root ,map.get(root.left)+1);
return true;
}else if (t2){
map.put(root ,map.get(root.right)+1);
return true;
}else{
return false;
}
}
public int getDis (TreeNode root) {
// write code here
TreeNode temp = root;
getMaxMin(temp);
temp = root;
getparent(temp,min,mapmin);
temp = root;
getparent(temp,max,mapmax);
int minpar = Integer.MAX_VALUE;
TreeNode targetNode = null;
for (TreeNode treeNode : mapmin.keySet()) {
if (mapmax.containsKey(treeNode)&&minpar>mapmax.get(treeNode) ){
minpar=mapmax.get(treeNode);
targetNode = treeNode;
}
}
return mapmax.get(targetNode) + mapmin.get(targetNode);
}
}
看了答案知道了用lca+depth的方式做,但是我很好奇我为什么是wa呜呜呜
package org.example;
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 树的根节点
* @return int整型
*/
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
public void getMaxMin(TreeNode root){
if(root==null){
return ;
}
max =Math.max(max,root.val);
min =Math.min(min,root.val);
getMaxMin(root.left);
getMaxMin(root.right);
}
Map<TreeNode,Integer> mapmin = new HashMap<>();
Map<TreeNode,Integer> mapmax = new HashMap<>();
public boolean getparent(TreeNode root,int target,Map<TreeNode,Integer> map){
if (root==null){
return false;
}
if(root.val==target){
map.put(root,0);
return true;
}
boolean t1 = getparent(root.left,target,map);
boolean t2 = getparent(root.right,target,map);
if (t1){
map.put(root ,map.get(root.left)+1);
return true;
}else if (t2){
map.put(root ,map.get(root.right)+1);
return true;
}else{
return false;
}
}
public int getDis (TreeNode root) {
// write code here
TreeNode temp = root;
getMaxMin(temp);
temp = root;
getparent(temp,min,mapmin);
temp = root;
getparent(temp,max,mapmax);
int minpar = Integer.MAX_VALUE;
TreeNode targetNode = null;
for (TreeNode treeNode : mapmin.keySet()) {
if (mapmax.containsKey(treeNode)&&minpar>mapmax.get(treeNode) ){
minpar=mapmax.get(treeNode);
targetNode = treeNode;
}
}
return mapmax.get(targetNode) + mapmin.get(targetNode);
}
}
全部评论
在网上除了ai没人愿意为你读这么长的代码的
相关推荐
10-18 12:02
西安电子科技大学 前端工程师 点赞 评论 收藏
分享
点赞 评论 收藏
分享
10-17 20:23
广东南华工商职业学院 Web前端 点赞 评论 收藏
分享