Pergunta de entrevista da empresa Tripadvisor

Given a root to a binary tree where each node holds an integer. Write a method that returns the sum of all the integers in the tree.

Respostas da entrevista

Sigiloso

25 de out. de 2013

Use recursion to add the current node's integer to the left subtree and right subtree's sum.

Sigiloso

9 de out. de 2014

In Python: def sum_tree_values(root): total_sum = root.value # Check if I reached a leaf if root.left is None and root.right is None: return total_sum else: # not a leaf if root.left is not None: # go to left subtree total_sum += sum_tree_values(root.left) if root.right is not None: # go to right subtree total_sum += sum_tree_values(root.right) return total_sum

Sigiloso

19 de nov. de 2015

Do any traversal, and then you can get the answer by adding the value of each node when you reach that node using referenced int passing, or updating a static variable.

Sigiloso

2 de fev. de 2021

There's quite an extended back and forth in actual interviews for questions like this, so nothing quite like real practice. The Prepfully TripAdvisor Software Engineer Intern experts have actually worked in this role, so they're able to do an honest-to-God accurate mock, which really puts you through the paces. prepfully.com/practice-interviews

Sigiloso

17 de nov. de 2013

struct node int data; struct node *next; int sum(node* current) if (current == NULL) return 0 return current->data+sum(current->left)+sum(current->right) total = sum(root)