有大神能教一下菜菜嘛?求二叉树的最小值节点和最大值节点的距离
看了答案知道了用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 18:42 贵州

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务