剑指offer-24-二叉树中和为某一值的路径
二叉树中和为某一值的路径
http://www.nowcoder.com/questionTerminal/b736e784e3e34731af99065031301bca
思路
字典序就是先序遍历顺序。
所以按字典序打印就好了,注意递归回溯,list.remove()
import java.util.ArrayList; public class Solution { ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list=new ArrayList<Integer>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { if(root==null){return result;} target-=root.val; list.add(root.val); if(target==0 && root.left==null && root.right==null){ result.add(new ArrayList<Integer>(list)); } FindPath(root.left,target); FindPath(root.right,target); list.remove(list.size()-1);//回溯 return result; } }
剑指offer与数据结构 文章被收录于专栏
本专栏包括剑指offer题目和一些刷题用的数据结构,单调栈,树状数组,差分数组,后面还会更新红黑树等较为复杂的数据结构