题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

1. 记录搜索路径——深度优先遍历——递归

public class Solution {
    //全局变量
    LinkedList<Integer> path = new LinkedList<>();
    ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        dfs(root,expectNumber);
        return arr;
    }
    public void dfs(TreeNode root,int num){
        if(root==null)return;
        path.add(root.val);
        num-=root.val;
        if(root.left==null&&root.right==null&&num==0){
            //path全局变量,故在此需要new一个空间来存放path的值
            arr.add(new ArrayList<>(path));
        }
        //若叶子结点,则不进入下面两个递归,从path中清除此叶子结点
        //深度优先,从最左侧搜索
        dfs(root.left,num);//左右子树分别再递归,重复这个过程
        dfs(root.right,num);//将问题分治到每个小子树
        //递归处理类似于栈,先处理完叶子结点,子结点递归结束被删除后,继续进行下一步
        //删除本结点(回退到上一层)
        path.removeLast();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务