您的位置:首页 > 其它

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

2017-06-04 22:27 483 查看
思路:
先求最大最小叶子节点,再求两节点的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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐