Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
<Solution>觀念和 Minimum Depth of Binary Tree 一樣,首先看 BFS 的解法
- 將 node 逐個丟到 queue 中,如果遇到 leaf node,檢查和是否等於要找的數,是的話就回傳 true,不是就繼續
當然,這個也有 recursive 的解法
- 空節點,回傳 false
- leaf node,檢查是否等於 sum 了
- node 還有任一子樹,繼續 recursive 下去。這邊只要有一個子樹為 true,整體就為 true
c++
kotlin
沒有留言:
張貼留言