LeetCode题解-112-Path Sum

来源:互联网 发布:网络视频电话软件 编辑:程序博客网 时间:2024/05/29 17:38

原题


原题链接https://leetcode.com/problems/path-sum/、

这里要注意的是路径必须是从root到leaf , 不能是中间一段。


解法概览

解法1:迭代法,深度优先

解法2:别人的更优雅的递归,参考https://discuss.leetcode.com/topic/3149/accepted-my-recursive-solution-in-java

解法3:我的递归,


解法1

思路分析

利用后序遍历,如果到了叶子节点并且路径的sum与给定的sum相同,那么返回true。后序遍历的思路与图解请见:http://blog.csdn.net/wangt443/article/details/51863846

代码

public class Solution112_iterator {    public boolean hasPathSum(TreeNode root, int sum) {        int currentSum = 0;        TreeNode lastVist = null;        Deque<TreeNode> stack = new LinkedList<TreeNode>();        if (root != null) {            stack.push(root);            currentSum += root.val;        }        while (!stack.isEmpty()){            while (stack.peek() != null){                TreeNode currentNode = stack.peek();                stack.push(currentNode.left);                if(currentNode.left != null)                    currentSum += currentNode.left.val;            }            stack.pop();            if (!stack.isEmpty()){                TreeNode currentNode = stack.peek();        //此时已是最左端,如果右子树为空则为叶子节点                if (currentNode.right == null && currentNode.left == null && currentSum == sum)                    return true;                if (currentNode.right == null || currentNode.right == lastVist){                    lastVist = stack.pop();                    currentSum -= lastVist.val;                    stack.push(null);                }                else {                    stack.push(currentNode.right);                    currentSum += currentNode.right.val;                }            }        }        return false;    }}

解法2

解题思路

每一次子递归都是将sum减去当前的val;

代码

public class Solution112_recursive_2 {    public boolean hasPathSum(TreeNode root, int sum) {        if(root == null)            return false;        if(root.left == null && root.right == null)            return sum == root.val;        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }}


解法3

解题思路

由于自己的解法使用的是加法,所以需要引入currentSum这第三个参数,没有解法2的“减法”简介。

代码

public class Solution112_recursive {    public boolean hasPathSum(TreeNode root, int sum) {        if (root == null)            return false;        else            return hasPathSumHelper(root, root.val, sum);    }    private  boolean hasPathSumHelper(TreeNode root, int currentSum ,int sum){        boolean lefHasPathSum = false, rightHasPathSum = false;        if (root == null)            return false;        if (root.left == null && root.right == null && currentSum == sum)            return true;        if (root.left != null){            lefHasPathSum = hasPathSumHelper(root.left, currentSum + root.left.val, sum);        }        if (root.right != null)            rightHasPathSum = hasPathSumHelper(root.right, currentSum + root.right.val, sum);        return lefHasPathSum || rightHasPathSum;    }}
0 0
原创粉丝点击