Diameter of Binary Tree - Better Design

前端 未结 11 2061
闹比i
闹比i 2020-12-23 15:14

I have written a code for finding diameter of Binary Tree. Need suggestions for the following:

  1. Can I do this without using static variable at class level?
11条回答
  •  无人及你
    2020-12-23 15:53

    Here is a solution in Java that has O(N) time complexity. It calculates the height in the same recursion when calculating the diameter. Reference Link

    private class HeightWrapper {
        int height = 0;
    }
    
    private int getDiameter_helper(BinaryTreeNode root, HeightWrapper wrapper) {
        if (root == null) {
            return 0; // diameter and height are 0
        }
    
        /* wrappers for heights of the left and right subtrees */
        HeightWrapper lhWrapper = new HeightWrapper();
        HeightWrapper rhWrapper = new HeightWrapper();
    
        /* get heights of left and right subtrees and their diameters */
        int leftDiameter = getDiameter_helper(root.left, lhWrapper);
        int rightDiameter = getDiameter_helper(root.right, rhWrapper);
    
        /* calculate root diameter */
        int rootDiameter = lhWrapper.height + rhWrapper.height + 1;
    
        /* calculate height of current node */
        wrapper.height = Math.max(lhWrapper.height, rhWrapper.height) + 1;
    
        /* calculate the diameter */
        return Math.max(rootDiameter, Math.max(leftDiameter, rightDiameter));
    }
    
    public int getDiameter(BinaryTreeNode root) {
        HeightWrapper wrapper = new HeightWrapper();
        return getDiameter_helper(root, wrapper);
    }
    

提交回复
热议问题