leetcode: Path Sum

来源:互联网 发布:android入门编程视频 编辑:程序博客网 时间:2024/06/05 17:01

思路你较简单,就是dfs前序遍历二叉树找到判断是否存在符合要求的路径。


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    boolean res = false;    public boolean hasPathSum(TreeNode root, int sum) {        if( root == null )        {            return res;        }        fun(root,sum);        return res;    }        void fun( TreeNode root,int sum )    {        sum = sum-root.val;         if( res == true )        {            return ;        }        if( root.right==null && root.left == null )        {            if( sum == 0 )            {                res = true;            }            return ;        }        boolean f1=true,f2=true;        if( root.left != null )        {            fun(root.left,sum);        }        if( root.right != null )        {            fun(root.right,sum);        }    }}


0 0
原创粉丝点击