Algorithm to print all paths with a given sum in a binary tree

后端 未结 18 1373
既然无缘
既然无缘 2020-12-24 07:04

The following is an interview question.

You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t

18条回答
  •  轮回少年
    2020-12-24 07:44

    One can reduce this tree to a weighted graph G, where each edge weight = sum of values in each of its nodes.

    Then, run Floyd-Warshall algorithm on the graph G. By inspecting elements in the resulting matrix, we can get all pairs of nodes between which the total sum is equal to the desired sum.

    Also, note that the shortest path the algorithm gives is also the only path between 2 nodes in this tree.

    This is just another approach, not as efficient as a recursive approach.

提交回复
热议问题