题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
解题思路
常规dfs,传引用的思路很好(要返回二维数组愁死我了,至于数组长度大的靠前,我没有操作。。)
Code
- cpp
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > allPath;
vector<int> path;
if(root) {
dfs(root, 0, expectNumber, path, allPath);
}
return allPath;
}
void dfs(TreeNode *root, int currentWeight, int expectNumber, vector<int> path, vector<vector<int> > &allPath) {
path.push_back(root->val);
currentWeight += root->val;
if(currentWeight > expectNumber) {
return ;
} else if(currentWeight == expectNumber) {
if(!root->left && !root->right) {
allPath.push_back(path);
}
return ;
}
if(root->left) {
dfs(root->left, currentWeight, expectNumber, path, allPath);
}
if(root->right) {
dfs(root->right, currentWeight, expectNumber, path, allPath);
}
//path.pop_back();
}
};
- java
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> path = new ArrayList<Integer>();
public void dfs(TreeNode root, int target, int w) {
if(w > target || root == null) return;
path.add(root.val);
if(w+root.val == target && root.left == null && root.right == null) {
result.add(new ArrayList<Integer>(path));
}
dfs(root.left, target, w+root.val);
dfs(root.right, target, w+root.val);
path.remove(path.size()-1);
}
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
dfs(root, target, 0);
return result;
}
}
总结
result.add(new ArrayList<Integer>(path));
将一维数组加入一个二维数组时,不能直接将引用加入,而是要new一个一维数组再加入, 否则加入的引用指向的对象会不断变化。