地址 https://www.acwing.com/problem/content/description/45/
输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
给出二叉树如下所示,并给出num=22。 5 / 4 6 / / 12 13 6 / / 9 1 5 1 输出:[[5,4,12,1],[5,6,6,5]]
树的处理 一半是递归
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> ret; void findPathInner(TreeNode* root, int sum, vector<int> v) { sum -= root->val; v.push_back(root->val); if (sum == 0 && root->left == NULL && root->right == NULL) { ret.push_back(v); return; } if(sum <0 ) return; if (root->left != NULL) { findPathInner(root->left, sum, v); } if (root->right != NULL) { findPathInner(root->right, sum, v); } } vector<vector<int>> findPath(TreeNode* root, int sum) { if (root == NULL) return ret; if (sum == 0) return ret; vector<int> v; sum -= root->val; v.push_back(root->val); if (sum < 0) return ret; if (sum == 0) { ret.push_back(v); return ret; } if (root->left != NULL) { findPathInner(root->left, sum, v); } if (root->right != NULL) { findPathInner(root->right, sum, v); } return ret; } };