112. Path Sum

xiaoxiao2021-02-28  57

1.递归搜索树

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

转载请注明原文地址: https://www.6miu.com/read-72011.html

最新回复(0)