1 不仅仅局限有无,针对所有情况的枚举处理
-
判断有无的逻辑和 给出所有可能的逻辑 ,很大差异
-
故意使用另外一个语言,理解边界的处理。
-
容易忘掉的递归的出口,还有路径的删除
语言的差异 Java vs C++
- root.val ,not root->val ;
- null not C++ NULL
- java vector结构的细微差异,链表添加链表!,链表remove注意传入int的意义
- {},0的边界输入
2 code
本轮重点是java
有2个版本
public class Solution {
//全局变量
public ArrayList<Integer> SmallList = new ArrayList<Integer>() ;
public ArrayList<ArrayList<Integer>> BigList = new ArrayList<ArrayList<Integer>> ();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
//001 check
if(root == null){
//deal 边界
return BigList;
}
//002 deep search
deepSearch(root,expectNumber);
//容易忘掉
return BigList;
}
public void deepSearch(TreeNode root,int expectNumber){
//stack push
Integer currInteger = Integer.valueOf(root.val);
SmallList.add(currInteger);
//found it;
if(root.left == null && root.right ==null && expectNumber == root.val){
//BigList.add(SmallList);
BigList.add(new ArrayList<Integer>(SmallList) );
}
//sub routine;
if(root.left !=null ){
deepSearch(root.left, expectNumber - root.val);
}
if(root.right !=null ){
deepSearch(root.right, expectNumber - root.val);
}
//final hard: stack pop; 容易出错
SmallList.remove(currInteger);
}
}
//这个版本 我还没提交过,仅仅参考
class Solution {
public:
using vvi = vector<vector<int>>;
using vi = vector<int>;
void dfs(TreeNode *root, int sum, vi &path, vvi &ret) {
path.push_back(root->val);
if (sum == root->val && !root->left && !root->right) {
ret.push_back(path);
}
if (root->left) dfs(root->left, sum - root->val, path, ret);
if (root->right) dfs(root->right, sum - root->val, path, ret);
path.pop_back(); // 代码走到这里,表明要回溯,代表当前path中的root节点我已经不需要了
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vvi ret;
vi path;
if (!root) return ret;
dfs(root, expectNumber, path, ret);
return ret;
}
};