Find the diameter of a binary tree

前端 未结 7 1122
旧时难觅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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 03:14

    You should use the height of the tree to calculate the diameter. Make a getHeight() function which will take the root of the tree as argument and return the height of the tree. Using this value and with the help of recursion we can calculate the diameter of the tree. Here is the code for it.....

    Function for calculating the diameter :-

    public static int getDiameter(BinaryTreeNode root) {        
      if (root == null)
        return 0;
    
    int rootDiameter = findHeight(root.getLeft()) + findHeight(root.getRight()) + 1;
    int leftDiameter = getDiameter(root.getLeft());
    int rightDiameter = getDiameter(root.getRight());
    
    return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
    }
    

    Function for calculating the height of tree:-

    public static int findHeight(BinaryTreeNode node) {
    if(node == null)
        return 0;
    
    else {
        return 1+Math.max(findHeight(node.left), findHeight(node.right));
    }
    }
    

提交回复
热议问题