LeetCode详解 之 Path Sum I and II(Java)

来源:互联网 发布:俄罗斯 中国 知乎 编辑:程序博客网 时间:2024/05/16 01:02
题目
Path Sum I:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
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
需要返回的是:
[   [5,4,11,2],   [5,8,4,5]]
也就是说第一题要求我们在一个二叉树上面,看是否有一条路径上所有的节点的值加起来等于我们所需要的这个固定的值。第二题难度加大了,在第一题的基础上面,要求找出所有的路径并且把这些路径用一个List表示出来。本题考察的依然是对树进行操作,以及对于双重List的用法,这对于刚刚接触数据结构和java的人来说还是略有难度。那么下面我们就一一来对这两道题目的程序进行详细的讲解。


程序及讲解:
那么第一题我给出了一种非常简单的方法,几行代码就可以把题目要求搞定,这样省去了大量的时间去进行下一环节的面试。
Path Sum I:
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        else if(root.left==null && root.right==null)
        return root.val==sum;
        else 
        sum=sum-root.val;
        return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
    }
}
在这里,我们直接进行了迭代(个人爱好),把程序交给下一步进行自动完成,只需要少量的代码来控制边界条件,此题过于简单就不做详细的解释了

Path Sum II:
public class Solution {
 public ArrayList> pathSum(TreeNode root, int sum) {
        ArrayList> result = new ArrayList>();
        if (root == null)
            return result;
        recursivePathSum(root, sum, new ArrayList(), result);
        return result;
    }
 
private void recursivePathSum(TreeNode root, int sum, ArrayList current,ArrayList> result) 
    {
        if (root == null)      
return;
        if (root.val == sum && root.left == null && root.right == null) {
            current.add(root.val);
            result.add(new ArrayList(current));
            current.remove(current.size()-1);
            return;
      }
 
        current.add(root.val);
        recursivePathSum(root.left, sum-root.val, current, result);
        recursivePathSum(root.right, sum-root.val, current, result);
        current.remove(current.size()-1);
    }
}

在这里,首先我们看到函数返回的是一个二维arraylist,这个是非常好用的一个java独有的一个东西,继承自List具有List的大量属性外,还具有add,remove等功能,可查阅API
首先check root,如果是null就返回刚刚建好的空的ArrayList,那么这个新建的方法中,没有返回任何值,但是却对result进行了一系列的操作,最终返回result。
那么重点就在这个我们新建的方法,如何才能很有效的实现这个方法:
如果只有一个根节点有值切恰恰等于那个值,OK,直接装上走人,如果没有,不着急,再进行遍历,我把根节点值保存在current这个arraylist中,再一次遍历左边的节点和右边的节点,直到程序结束。
细节在于每次current完了以后要对他的size进行一次remove
arraylist.remove(index)的方法是remove掉index这个点的值。
0 0
原创粉丝点击