zoukankan      html  css  js  c++  java
  • 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]
    ]

    path sum 是这个的基础,

    path sum I是问存不存在这样一条路径,使得路径和为sum。使用递归。深度优先遍历的递归求法,见树的广度优先遍历和深度优先遍历(递归非递归、Java实现)
    这题是要让求出这样的路径,也是同样地思路,使用递归,因为要添加到list中,所以每遍历一个就要往list中添加,直到叶子节点,判断是否等于sum,当等于,表明该路径符合,将list加到结果集中,同时别忘了,要删除叶子节点,再返回,进行下一个叶子判断。
    如果不满足要求或者不是叶子节点,则将该节点加到list中,并继续遍历左右子树,遍历完了,也要删除该节点,返回上一层。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            if(root==null) return res;
            helper(root,sum,res,new ArrayList<Integer>());
            return res;
        }
        public void helper(TreeNode root,int sum,List<List<Integer>> res,List<Integer> list){
            if(root==null) return;   //使用这个,就不用再讨论左右子树谁为空了
            
            if(root.left==null&&root.right==null&&root.val==sum){
                list.add(root.val);
                res.add(new ArrayList<Integer>(list));
                list.remove(list.size()-1);   //要将其删除再返回上一层
                return ;
            }else{
                list.add(root.val);
                helper(root.left,sum-root.val,res,list);
                helper(root.right,sum-root.val,res,list);
                list.remove(list.size()-1);   //将其删除再返回上一层。
            }
        }
    }
  • 相关阅读:
    code-breaking picklecode中对signed_cookies引擎分析
    [一道蓝鲸安全打卡Web分析] 文件上传引发的二次注入
    攻防世界Web新手解析
    面向对象相关
    面试第二篇
    函数相关
    python复习目录
    面试第一篇
    Django Rest Framework进阶二
    Django Rest Framework进阶一
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8253554.html
Copyright © 2011-2022 走看看