Sobes.tech
Middle

Given a tree with interface INode (value: number, left?: INode, right?: INode), write a function that traverses the tree and returns the sum of all values.

sobes.tech AI

Answer from AI

Here's an example of a TypeScript function that recursively traverses a tree with the INode interface and returns the sum of all value fields:

interface INode {
  value: number;
  left?: INode;
  right?: INode;
}

function sumTree(node?: INode): number {
  if (!node) return 0;
  return node.value + sumTree(node.left) + sumTree(node.right);
}

// Example usage:
const tree: INode = {
  value: 10,
  left: { value: 5 },
  right: { value: 15, left: { value: 3 } }
};

console.log(sumTree(tree)); // 33
Given a tree with interface INode (value: number… - sobes.tech