No11、求二叉树中节点的最大距离...

来源:互联网 发布:淘宝旺旺名称在哪里看 编辑:程序博客网 时间:2024/06/05 20:53
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,

求一棵二叉树中相距最远的两个节点之间的距离。


解题思路:

对于任意一个节点p,以它为根节点的二叉树中最远的距离是:

Max(p->leftNode.height+1+p->rightNode.height+1,maxDistance(p->leftNode),maxDistance(p->rightNode));

即对于p来说,它添加进二叉树对最远距离造成的影响就是它在左子树中的高度加上它在右子树中的高度,然后与原有的最远距离(左子树中的最远距离,右子树中的最远距离)相比即可得到结果


package com;public class Q11 {static int max = 0;public static Node init(){Node a = new Node('a');Node b = new Node('a');Node c = new Node('a');Node d = new Node('a');Node e = new Node('a');Node f = new Node('a');Node g = new Node('a');Node h = new Node('a');Node i = new Node('a');Node j = new Node('a');a.leftChild = b;//a.RightChild = c;b.leftChild = d;d.RightChild = e;c.leftChild = f;c.RightChild = g;d.leftChild = h;f.RightChild = i;i.leftChild = j;return a;}public static int getMaxLength(Node node)           //递归主体函数,返回该节点作为根节点的子树的高度{if(node == null)return 0;int llength = 0;                            //记录左子树的高度int rlength = 0;                            //记录右子树的高度    if(node.leftChild != null)                  //得到该节点在它的左子树中的高度llength = getMaxLength(node.leftChild)+1;elsellength = 0;if(node.RightChild != null)                  //得到该节点在它的右子树中的高度rlength = getMaxLength(node.RightChild) +1;elserlength = 0;int sum = llength+rlength;                   //最远距离经过该节点的时候if(sum>max)                                  //与当前的max相比max = sum;                           //在之前getMaxLength()函数递归调用的时候,max已经与左子树中的最远距离、右子树中的最远距离比较了           return llength>rlength?llength:rlength;}public static void main(String[] args) {Node root = init();getMaxLength(root);System.out.println(max);}}


原创粉丝点击