Path Sum

来源:互联网 发布:模仿声音软件下载 编辑:程序博客网 时间:2024/06/08 01:05

Notes:不太会用递归啊

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<Integer> list = new ArrayList<Integer>();    public void getLength(TreeNode root, int treeLength){        if(root.left == null && root.right == null){            list.add(treeLength + root.val);        }        if(root.left != null){            getLength(root.left, treeLength + root.val);        }        if(root.right != null){            getLength(root.right, treeLength + root.val);        }    }    public boolean hasPathSum(TreeNode root, int sum) {        int treeLength = 0;        if(root == null){            return false;         }                getLength(root, treeLength);                for(int i = 0; i < list.size(); i++)          {              if(list.get(i) == sum){                return true;            }          }        return false;    }}
简单的递归方法:

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public boolean hasPathSum(TreeNode root, int sum) {        int treeLength = 0;        if(root == null){            return false;         }        if(root.left == null && root.right == null) return root.val == sum;        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);    }}



0 0
原创粉丝点击