Home > Software engineering >  Diameter of a binary tree - returning an array
Diameter of a binary tree - returning an array

Time:02-05

I get that the idea is to traverse from each end node, find the larger height of left and right, and add them to find the biggest diameter. In most solutions, they're using max[0] as arg and return that as well. I tried a different approach, but somehow it passed all tests except the one that has the biggest diameter without passing through the root. What went wrong here?

var diameterOfBinaryTree = function(root) {
    const result = dfs(root, 0);
    return result[1];
};

function dfs(root, max) {
    if (!root) return [0, max];
    const left = dfs(root.left, max);
    const right = dfs(root.right, max);

    const height = 1   Math.max(left[0], right[0]);
    max = Math.max(max, left[0]   right[0]);

    return [height, max];
}

CodePudding user response:

You're looking for

function diameterOfBinaryTree(root) {
    return dfs(root).diameter;
}

function dfs(node) {
    if (!node) return {height: 0, diameter: 0};
    const left = dfs(node.left);
    const right = dfs(node.right);

    const height = 1   Math.max(left.height, right.height);
    const diameter = Math.max(left.height   right.height, left.diameter, right.diameter);

    return {height, diameter};
}
  • Related