網易——求二叉樹最大葉子節點到最小葉子節點的距離

有一棵二叉樹,樹上每個點標有權值,權值各不相同,請設計一個算法算出權值最大的葉節點到權值最小的葉節點的距離。二叉樹每條邊的距離爲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;
    }
}


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