求二叉树中节点的最大距离 即二叉树中相距最远的两个节点之间的距离

来源:互联网 发布:北大青鸟学软件编程 编辑:程序博客网 时间:2024/05/22 17:06
 <span style="font-size:18px;">        public static int height(TreeNode t)    // postcondition: returns height of tree with root t    {        if (t == null)        {            return 0;        }        else        {            return 1+Math.max(height(t.left),height(t.right));        }    }   public static int getMaxdis(TreeNode tree){   // post: return Max distance of tree   if (tree == null) return 0;   int lheight = height(tree.left);                  int rheight = height(tree.right);   int ldiameter = getMaxdis(tree.left);   int rdiameter = getMaxdis(tree.right);   return Math.max(lheight + rheight,Math.max(ldiameter,rdiameter));   }</span>

0 0
原创粉丝点击