Diameter of Binary Tree - Better Design

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

    Neat and clean solution:

    // way to use below util function:
    prop p = new prop();
    diameterUtil(root, p);
    System.out.println(p.d);
    
    class prop {
        int h;
        int d;
    }
    
    private void diameterUtil(Node n, prop p) {
        if (n == null) {
            p.h = 0;
            p.d = 0;
            return;
        }
        prop lp = new prop();
        prop rp = new prop();
        diameterUtil(n.left, lp);
        diameterUtil(n.right, rp);
        p.h = Math.max(lp.h, rp.h) + 1;
        p.d = Math.max((lp.h + rp.h + 1), Math.max(lp.d, rp.d));
    }
    

提交回复
热议问题