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

后端 未结 18 1399
既然无缘
既然无缘 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条回答
  •  猫巷女王i
    2020-12-24 07:28

    Update: I see now that my answer does not directly answer your question. I will leave it here if it proves useful, but it needs no upvotes. If not useful, I'll remove it. I do agree with @nhahtdh, however, when he advises, "Reuse your algorithm with all other nodes as root."

    One suspects that the interviewer is fishing for recursion here. Don't disappoint him!

    Given a node, your routine should call itself against each of its child nodes, if it has any, and then add the node's own datum to the return values, then return the sum.

    For extra credit, warn the interviewer that your routine can fail, entering an bottomless, endless recursion, if used on a general graph rather than a binary tree.

提交回复
热议问题