leetcode 112

路径总和

Posted by Static on July 7, 2020

题目链接:https://leetcode-cn.com/problems/path-sum/

题目描述


分析

1. 添加到数组中,再排序取值


代码实现

public enum Q112 {
    instance;
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)return false;
        return pre(root,sum,root.val);
    }

    private boolean pre(TreeNode node,int sum,int current){
        if(node==null){
            return false;
        }
        if((node.left==null&&node.right==null)&&current==sum){
            return true;
        }
        boolean leftResult=false;
        if(node.left!=null){
            leftResult= pre(node.left,sum,current+node.left.val);
        }
        boolean rightResult=false;
        if(node.right!=null){
            rightResult= pre(node.right,sum,current+node.right.val);
        }
        return leftResult||rightResult;
    }

    public static void main(String[] args) {
        TreeNode root=new TreeNode( 5);
        root.left=new TreeNode(4);
        root.right=new TreeNode(8);

        root.left.left=new TreeNode(11);
        root.right.left=new TreeNode(13);
        root.right.right=new TreeNode(4);

        root.left.left.left=new TreeNode(7);
        root.left.left.right=new TreeNode(2);
        root.right.right.right=new TreeNode(1);
        // assert true
        System.out.println(Q112.instance.hasPathSum(root,22));

        TreeNode root1=new TreeNode( 1);
        root1.left=new TreeNode(2);
        // assert false
        System.out.println(Q112.instance.hasPathSum(root1,2));

        TreeNode root2=new TreeNode( -2);
        root2.right=new TreeNode(-3);
        // assert true
        System.out.println(Q112.instance.hasPathSum(root2,-5));
    }
}

The most valuable way of reading is to gradually follow the natural order of reading in order to achieve the state if exquisite. Zhu Xi

读书之法,莫贵于循序而致精。 – 朱熹