本文共 985 字,大约阅读时间需要 3 分钟。
样例
给定一个二叉树,和 目标值 = 5
:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4]]
解法:DFS,注意路径和的概念,要到叶子节点
AC代码:
class Solution {public: /* * @param root: the root of binary tree * @param target: An integer * @return: all valid paths */ vector> binaryTreePathSum(TreeNode * root, int target) { // write your code here vector > res; if(!root){ return res; } vector a; TreePathSum(root, target, 0, a, res); return res; } void TreePathSum(TreeNode * root, int target,int now, vector & a, vector > &res) { // write your code here now += root->val; a.push_back(root->val); if(now == target){ if(!root->right && !root->left ) res.push_back(a); } if(root->left){ TreePathSum(root->left, target, now, a, res); a.pop_back(); } if(root->right){ TreePathSum(root->right, target, now, a, res); a.pop_back(); } return ; }};
转载地址:http://axoli.baihongyu.com/