C# easy to understand


  • 2
    Y

    calculate depth of both sub-tree of every node

    int maxDiameter = 0;
            public int DiameterOfBinaryTree(TreeNode root)
            {
                if (root == null)
                    return 0;
    
                DiameterOfBinaryTree(root.left);
                maxDiameter = Math.Max(findDepth(root.left) + findDepth(root.right), maxDiameter);            
                DiameterOfBinaryTree(root.right);
    
                return maxDiameter;
            }
            int findDepth(TreeNode node)
            {
                if (node == null)
                    return 0;
    
                return 1 + Math.Max(findDepth(node.left), findDepth(node.right));
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.