微软算法100题11 求二叉树中两节点之间的最大距离

第11 题
求二叉树中节点的最大距离...
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离

 

 

思路:  一棵树中节点的最大距离,对于根节点来说,可以看做是左子树的最大深度加右子树的最大深度在加上左右各一个深度 (leftDepth + rightDepth + 1 + 1),但有种情况是假如根节点的左子节点,该节点分别有很深的左子树和右子树,则整棵树具有最大间距的节点,可能都分布在该左子树上,压根不会经过根节点。所以考虑到这种情况,在进行递归计算时,需要比较根据深度得到的最大距离和实际左右节点最大距离,找出较大的那个

 

 1 package com.rui.microsoft;
 2 
 3 public class Test11_MaxDistanceBST {
 4 
 5     public static void main(String[] args) {
 6         Node n1 = new Node(1);
 7         Node n2 = new Node(2);
 8         Node n3 = new Node(3);
 9         Node n4 = new Node(4);
10         Node n5 = new Node(5);
11         Node n6 = new Node(6);
12         Node n7 = new Node(7);
13         Node n8 = new Node(8);
14         Node n9 = new Node(9);
15         
16         n1.left = n2; n1.right = n3;
17         n2.left = n4; n2.right = n5;
18         n4.left = n6;
19         n5.right = n7;
20         n6.left = n8;
21         n7.right = n9;
22         
23         int maxDistance = Test11_MaxDistanceBST.calulate(n1).dist;
24         System.out.println(maxDistance);
25     }
26     
27     public static Result calulate(Node node){
28         //if current node doesn't exist
29         //then return 0 distance and -1 depth
30         if(null == node) return new Result(0, -1);
31         
32         Result leftRes = calulate(node.left);
33         Result rightRes = calulate(node.right);
34         
35         //First let's assume the max distance is the left node's depth + right node's depth + left single depth + right single depth
36         int maxDis = leftRes.depth + rightRes.depth + 1 + 1;
37         //Then compare it with real distance value and get the largest one
38         maxDis = max(maxDis, max(leftRes.dist, rightRes.dist));
39         
40         //return the result object, whose depth value should be choosen by comparing left node's depth and right node's depth and plus one single depth value
41         return new Result(maxDis, max(leftRes.depth, rightRes.depth) + 1);
42         
43     }
44     
45     private static int max(int i, int j){
46         return i > j ? i:j;
47     }
48     
49     static class Result{
50         int dist;
51         int depth;
52         Result(int dist, int depth){
53             this.dist = dist;
54             this.depth = depth;
55         }
56     }
57     
58     static class Node {
59         int value;
60         Node left;
61         Node right;
62         public Node(int v){
63             this.value = v;
64         }
65     }
66 }

 

posted @ 2015-10-23 15:19  蟹粉小笼包  阅读(276)  评论(0编辑  收藏  举报