天天看點

Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:

Given the below binary tree and <code>sum = 22</code>,

return

與Path Sum相比,本題是求出路徑,是以,在找到滿足的路徑之後,不能直接傳回,而是将其添加到一個vector&lt;vector&lt;int&gt;&gt;中。在查找的過程中,每經過一個結點,先使用一個vector&lt;int&gt;将該路徑中的所有結點記錄下來。由于vector&lt;vector&lt;int&gt;&gt;是用來記錄所有滿足的路徑的,是以傳遞引用給它是為了對它的每一個改動都是對其本身的操作,而不是對其副本的操作,使用來傳回找到的所有路徑。使用的vector&lt;int&gt;隻是拷貝操作,是以都是對其副本的操作,不會對原始的vector&lt;int&gt;有影響。

C++代碼實作:

運作結果:

Path Sum II

繼續閱讀