Find the diameter of a binary tree

前端 未结 7 1004
旧时难觅i
旧时难觅i 2021-01-01 03:01

I am trying to find the diameter of a binary tree (Path length between any two nodes in the tree containing maximum number of nodes.) in java.

my code snippet:

7条回答
  •  执笔经年
    2021-01-01 03:19

    Algo takes O(n). Calculates height and path at the same time.

    public static int findLongestPath(TreeNode root)
    {
      // longest path = max (h1 + h2 + 2, longestpath(left), longestpath(right);
    
      int[] treeInfo = longestPathHelper(root);
    
      return treeInfo[0];
    }
    
    private static int[] longestPathHelper(TreeNode root)
    {
      int[] retVal = new int[2];
    
      if (root == null)
      {
         //height and longest path are 0
         retVal[0] = 0;
         retVal[1] = 0;
      }
    
      int[] leftInfo = longestPathHelper(root.getLeft());
      int[] rightInfo = longestPathHelper(root.getRight());
    
      retVal[0] = Math.max(leftInfo[1] + rightInfo[1] + 2, Math.max(leftInfo[0], rightInfo[0]));
      retVal[1] = Math.max(leftInfo[1], rightInfo[1]) + 1;
    
      return retVal;
    }
    

提交回复
热议问题