题目描述
输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
分析:
1、因为要包含所有可能的路径,因此返回的结果res为二维数组,用一维数组path保存满足条件的单条路径的结点值
2、从根节点开始,若当前结点为null,直接返回res
3、若当前结点为叶子结点,且结点的值正好和目标值相等,则将该单条路径的结点值数组path加入res
4、将目标值target减去当前结点的值val作为下一个节点的目标值,再分别将当前结点的左节点和右结点分别作为根节点递归求解
5、若当前结点的左右子节点都为空,则回退到上一个结点,即去除path的最后一个值,继续判断
Java代码:
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null)
return res;
path.add(root.val);
boolean flag = (root.left == null) && (root.right == null);
if((root.val == target) && flag)
res.add(new ArrayList<Integer>(path));
FindPath(root.left, target-root.val);
FindPath(root.right, target-root.val);
if(path.size() != 0)
path.remove(path.size()-1);
return res;
}
}
C++代码:
class Solution {
public:
vector<vector<int> > res;
vector<int> path;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if(root == NULL)
return res;
path.push_back(root->val);
bool flag = (root->left == NULL && root->right == NULL);
if((expectNumber == root->val) && flag)
{
res.push_back(path);
}
FindPath(root->left, expectNumber-root->val);
FindPath(root->right, expectNumber-root->val);
if(path.size() != 0)
path.pop_back();
return res;
}
};