Diameter of Binary Tree - Better Design

前端 未结 11 2062
闹比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:55

    public class NodeWrap{
        int height = 0;
        int maxLength = 0;
        public NodeWrap(int h, int m){
            height = s;
            maxLength = m;
        }
    }
    
    
    public NodeWrap getDiameter(BinaryNode root){
        if(root == null){
            return new NodeWrap(0, 0);
        }
    
        NodeWrap left = getDiameter(root.left);
        NodeWrap right = getDiameter(root.right);
    
        int height = Math.max(left.height + right.height) + 1;
    
        int maxLength = Math.max(left.maxLength, right.maxLength);
        if(left.height != 0 && right.height != 0){
            maxLength = Math.max(left.height + right.height + 1, maxLength);
        }
        return new NodeWrap(singleLength, maxLength);
    }
    

提交回复
热议问题