题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
List<List<int>> returnList = new List<List<int>>();
List<int> tempList = new List<int>();
public List<List<int>> FindPath(TreeNode root, int expectNumber)
{
// write code here
if (root==null)
{
return returnList;
}
tempList.Add(root.val);
//如果递归到叶节点,如果和为expectNumber,则添加路径list
if (expectNumber==root.val&&root.left==null&&root.right==null)
{
returnList.Add(new List<int>(tempList));
}
if (expectNumber-root.val>=0)
{
FindPath(root.left, expectNumber - root.val);
FindPath(root.right, expectNumber - root.val);
}
//递归到叶节点如果不符合expectNumber,则回退到上一个根节点,然后递归回退到的根节点的右子节点
tempList.RemoveAt(tempList.Count - 1);
return returnList;
}
}