Find the diameter of a binary tree

前端 未结 7 1102
旧时难觅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条回答
  •  爱一瞬间的悲伤
    2021-01-01 03:33

    int max=0;
    public int diameter(Tree root) {
      if(root==null) return 0;
      int l=diameter(root.left);
      int r=diameter(root.right);
      max=Math.max(max,l+r+1);
      return l>r:l+1:r+1;
    }
    

    max is the max diameter.

提交回复
热议问题