网易——求二叉树最大叶子节点到最小叶子节点的距离

有一棵二叉树,树上每个点标有权值,权值各不相同,请设计一个算法算出权值最大的叶节点到权值最小的叶节点的距离。二叉树每条边的距离为1,一个节点经过多少条边到达另一个节点为这两个节点之间的距离。

给定二叉树的根节点root,请返回所求距离。


import java.util.*;


/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class Tree {
    public int getDis(TreeNode root) {
        // write code here
        if(root == null||(root.left == null&&root.right == null))
            return 0;
        TreeNode[] tn=new TreeNode[2];
        int[] max={Integer.MIN_VALUE};
        int[] min={Integer.MAX_VALUE};
        findNode(root,tn,max,min);
        TreeNode maxNode=tn[0];
        TreeNode minNode=tn[1];
        if(maxNode == minNode){
            return 0;
        }
        TreeNode lca=LCA(root,maxNode,minNode);
        int[] count=new int[1];
        distance(lca,maxNode,0,count);
        int maxpath=count[0];
        distance(lca,minNode,0,count);
        int minpath=count[0];
        return maxpath+minpath;
    }
    
    //找到最大最小叶节点
    public void findNode(TreeNode root,TreeNode[] tn,int[] max,int[] min)
        {
        if(root == null){
            return;
        }
        if(root.left == null&&root.right == null){
            if(root.val > max[0]){
                tn[0]=root;
                max[0]=root.val;
            }
            if(root.val < min[0]){
                tn[1]=root;
                min[0]=root.val;
            }
            return;
        }
        findNode(root.left,tn,max,min);
        findNode(root.right,tn,max,min);
    }
    //找到这两个点的LCA
    public TreeNode LCA(TreeNode root,TreeNode max,TreeNode min){
        if(root == null||root == max||root == min){
            return root;
        }
        TreeNode left=LCA(root.left,max,min);
        TreeNode right=LCA(root.right,max,min);
        if(left!=null&&right!=null){
            return root;
        }
        if(left!=null){
            return left;
        }
        if(right!=null){
            return right;
        }
        return null;
    }
      //分别找到lca和两个点的距离
    public boolean distance(TreeNode root,TreeNode node,int cur,int[] count){
        if(root == null||node == null){
            return false;
        }
        if(root == node){
            count[0]=cur;
            return true;
        }
        cur++;
        boolean flag=distance(root.left,node,cur,count);
        if(flag == false){
            flag=distance(root.right,node,cur,count);
        }
        return flag;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章