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

来源:互联网 发布:利用python写网络爬虫 编辑:程序博客网 时间:2024/06/05 03:54

题目:如果我们把二叉树看成一个图,

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

分析:

计算一个二叉树的最大距离有两个情况:

  • 情况A: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
  • 情况B: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。

只需要计算这两个情况的路径距离,并取其大者,就是该二叉树的最大距离。


package com.itcast.demo.random;import java.util.Arrays;import java.util.Scanner;//import com.itcast.demo.random.TreeNodeDemo.Node;public class StringDemo {private Node root;   static int  MaxLen=0;     private class Node {          private Node pLeft;          private Node pRight;          private int data;          int MaxLeft;          int MaxRight;        public Node(int data) {              this.pLeft = null;              this.pRight = null;              this.data = data;          }      }      public StringDemo() {          root = null;      }     public void buildTree(Node node, int data) {          if (root == null) {              root = new Node(data);          } else {              if (data < node.data) {                  if (node.pLeft == null) {                      node.pLeft = new Node(data);                  } else {                      buildTree(node.pLeft, data);                  }              } else {                  if (node.pRight == null) {                      node.pRight = new Node(data);                  } else {                      buildTree(node.pRight, data);                  }              }          }      }     public void FindMaxLen(Node pRoot){          if(pRoot==null){              return;          }          if(pRoot.pLeft==null){              pRoot.MaxLeft=0;          }          if(pRoot.pRight==null){              pRoot.MaxRight=0;          }          if(pRoot.pLeft!=null){              FindMaxLen(pRoot.pLeft);          }          if(pRoot.pRight!=null){              FindMaxLen(pRoot.pRight);          }          if(pRoot.pLeft!=null){              int nTempMax=0;              nTempMax=pRoot.pLeft.MaxLeft>pRoot.pLeft.MaxRight?pRoot.pLeft.MaxLeft:pRoot.pLeft.MaxRight;              pRoot.MaxLeft=nTempMax+1;          }          if(pRoot.pRight!=null){              int nTempMax=0;              nTempMax=pRoot.pRight.MaxLeft>pRoot.pRight.MaxRight?pRoot.pRight.MaxLeft:pRoot.pRight.MaxRight;              pRoot.MaxRight=nTempMax+1;          }          if(pRoot.MaxLeft+pRoot.MaxRight>MaxLen){              MaxLen=pRoot.MaxLeft+pRoot.MaxRight;          }      }  public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println("请随意输入一串数字:");Scanner sc = new Scanner(System.in);String[] num = null;num = sc.nextLine().split(" ");int[] number = new int[num.length];for (int i = 0; i < number.length; i++) {number[i] = Integer.valueOf(num[i]);}Arrays.sort(number);StringDemo tn = new StringDemo();  for (int i = 0; i < number.length; i++) {              tn.buildTree(tn.root, number[i]);          }   tn.FindMaxLen(tn.root);  System.out.println(MaxLen);}}