每日一题 2019 - 04 - 26
题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
1 | 5 |
Return:
1 | [ |
解法:
这个题让找出二叉树上等于给定值和的路径结点,整体来说深度优先遍历就可以解决问题,但是需要注意两个地方:
- 返回的路径一定是从根节点到最低层的路径记录
- 每一层完成遍历一定要让当前记录的
vector
与sum_value
删除当前层的记录,避免影响进一步的搜索;
代码:
1 | /** |