二叉树前序遍历
import java.util.*;
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> res = new ArrayList();
private LinkedList path = new LinkedList();
public ArrayList> FindPath(TreeNode root,int expectNumber) {
if(root == null){
return res;
}
preOrder(root,expectNumber);
return res;
}
public void preOrder(TreeNode root,int remainder){
if(root.left == null && root.right == null){
if(root.val == remainder){
path.add(root.val);
res.add(new ArrayList(path));
path.removeLast();
}
return;
}
path.add(root.val);
if(root.left != null){
preOrder(root.left,remainder-root.val);
}
if(root.right != null){
preOrder(root.right,remainder-root.val);
}
path.removeLast();
}
}
京公网安备 11010502036488号