二叉树根节点到叶子节点和为指定值的路径
package com.wy.tree;
import com.wy.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class 二叉树根节点到叶子节点和为指定值的路径 {
public ArrayList<ArrayList<Integer>> pathSum1(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
dfs1(root, sum, new ArrayList<>(), result);
return result;
}
public ArrayList<ArrayList<Integer>> pathSum2(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
Stack<TreeNode> stackNode = new Stack<>();
Stack<ArrayList<Integer>> stackList = new Stack<>();
stackNode.add(root);
ArrayList<Integer> list = new ArrayList<>();
list.add(root.val);
stackList.add(list);
while (!stackNode.isEmpty()){
TreeNode node = stackNode.pop();
ArrayList<Integer> tempList = stackList.pop();
if(node.left == null && node.right == null && node.val == sum){
res.add(tempList);
}
if(node.right != null){
tempList.add(node.right.val);
stackList.add(new ArrayList<>(tempList));
node.right.val += node.val;
stackNode.push(node.right);
tempList.remove(tempList.size() - 1);
}
if(node.left != null){
tempList.add(node.left.val);
stackList.add(new ArrayList<>(tempList));
node.left.val += node.val;
stackNode.push(node.left);
tempList.remove(tempList.size() - 1);
}
}
return res;
}
public void dfs1(TreeNode root, int sum, List<Integer> list, List<ArrayList<Integer>> result){
if(root == null){
return;
}
ArrayList<Integer> subList = new ArrayList<>(list);
subList.add(root.val);
if(root.left == null && root.right == null){
if(sum == root.val){
result.add(subList);
}
return;
}
dfs1(root.left, sum - root.val, subList, result);
dfs1(root.right, sum - root.val, subList, result);
}
public void dfs2(TreeNode root, int sum, List<Integer> list,
List<ArrayList<Integer>> result) {
if (root == null)
return;
list.add(new Integer(root.val));
if (root.left == null && root.right == null) {
if (sum == root.val)
result.add(new ArrayList(list));
list.remove(list.size() - 1);
return;
}
dfs2(root.left, sum - root.val, list, result);
dfs2(root.right, sum - root.val, list, result);
list.remove(list.size() - 1);
}
}