[LeetCode]Path Sum,解题报告

前言

习惯的写下前言,最近生活一直过得很平稳,根据《尚学堂马士兵》的教程把javaSE的基础学完了,顺便把《java核心技术》基础篇看完了,准备继续跟着尚学堂马士兵的教程学习java EE

篮球最近会跳投了,而且还挺准,有了新的东西大胆的尝试总比固守原有的东西强,因为你一直在进步

题目

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,



return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.


思路

我第一感觉就是用DFS的思想,遍历二叉树到根节点,判断是否有满足条件的path


AC代码

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public static boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        } else {
           return bfsBtree(root, root.val, sum); 
        }
    }
    
    public static boolean bfsBtree(TreeNode root, int total, int sum) {
        if (root.left == null && root.right == null) {
            if (total == sum) {
                return true;
            } else {
                return false;
            }
        } else {
            boolean flagl, flagr;
            flagl = flagr = false;
            
            if (root.left != null) {
                flagl = bfsBtree(root.left, total + root.left.val, sum);
            }
            
            if (root.right != null) {
                flagr = bfsBtree(root.right, total + root.right.val, sum);
            }
            
            return flagl || flagr;
        }
    }
}


你可能感兴趣的:([LeetCode]Path Sum,解题报告)