Find the diameter of a binary tree

前端 未结 7 1097
旧时难觅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条回答
  •  Happy的楠姐
    2021-01-01 03:26

    I suggest the following:

    public static TreeAttr calcTreeDiameter(Node root) {
        if (root == null)
            return new TreeAttr(0, 0);
    
        TreeAttr leftAttr = calcTreeDiameter(root.getLeft());
        TreeAttr rightAttr = calcTreeDiameter(root.getRight());
    
        int maxDepth = Math.max(leftAttr.depth, rightAttr.depth);
        int maxDiam = Math.max(leftAttr.diameter, rightAttr.diameter);
        maxDiam = Math.max(maxDiam, leftAttr.depth + rightAttr.depth + 1);
    
        return new TreeAttr(maxDiam, maxDepth + 1);
    }
    

    The TreeAttr is a simple structure containing the diameter and depth of a subtree. Both should be passed in the recursion, since the optimum may either come from one of the subtrees, or from the concatenation of the longest paths.

提交回复
热议问题