搜狐研究院 求二叉树最大叶子节点到最小叶子节点的距离

思路:

先求最大最小叶子节点,再求两节点的LCA(最近公共祖先),求两节点到LCA距离。

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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值