NC_9_HAS_PATH_SUM

package org.example.interview.practice;

/**
 * @author xianzhe.ma
 * @date 2021/8/23
 */

public class NC_9_HAS_PATH_SUM {

    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if (root == null) {
            return false;
        }

        if (root.left== null && root.right == null && sum == root.val) {
            return true;
        }

        return hasPathSum(root.left,sum - root.val) || hasPathSum(root.right,sum - root.val);
    }

    public static void main (String[] args) {
        TreeNode node = new TreeNode(1);
        Boolean flag= hasPathSum(node, 1);
        System.out.println(flag);
    }
}

 

posted on 2022-02-10 15:37  MaXianZhe  阅读(29)  评论(0编辑  收藏  举报

导航