题目113. Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/
4 8
/ /
11 13 4
/ \ /
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
思路: 参考112. Path Sum
1,递归
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> result = new ArrayList<Integer>();
dfs(root,0,sum,result,results);
return results;
}
private void dfs(TreeNode root, int curSum, int sum, List<Integer> result, List<List<Integer>> results){
if(root == null){
return;
}
if(root.left == null && root.right == null){
if (curSum + root.val == sum){
result.add(root.val);
results.add(result);
}
return;
}
result.add(root.val);
if(root.left != null && root.right != null){
List<Integer> tempResult = new ArrayList<Integer>();
tempResult.addAll(result);
dfs(root.left,curSum + root.val,sum,tempResult,results);
dfs(root.right,curSum + root.val,sum,result,results);
}else if(root.left != null && root.right == null){
dfs(root.left,curSum + root.val,sum,result,results);
}else if(root.left == null && root.right != null){
dfs(root.right,curSum + root.val,sum,result,results);
}
}
2,利用后序遍历
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(root == null){
return result;
}
//根节点到栈顶节点的路径
Stack<TreeNode> pathsStack = new Stack<TreeNode>();
TreeNode node = root;
TreeNode tempNode = null;
boolean hasVisited = true;
do{
while(node != null){
pathsStack.push(node);
node = node.left;
}
tempNode = null;
hasVisited = true;
while(!pathsStack.empty() && hasVisited){
node = pathsStack.peek();
if(tempNode == node.right){
tempNode = pathsStack.pop();
//判断根节点到叶子节点的路径和
if(tempNode.left == null && tempNode.right == null){
int pathSum = tempNode.val;
List<Integer> path = new LinkedList<Integer>();
for(TreeNode treeNode : pathsStack){
pathSum += treeNode.val;
path.add(treeNode.val);
}
if(sum == pathSum){
result.add(path);
path.add(tempNode.val);
}
}
}else{
node = node.right;
hasVisited = false;
}
}
}while(!pathsStack.empty());
return result;
}