?LeetCode刷題實(shí)戰(zhàn)112:路徑總和
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?路徑總和,我們先來看題面:
https://leetcode-cn.com/problems/path-sum/
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
題意

解題
class?Solution?{
????public?boolean?hasPathSum(TreeNode root, int?sum)?{
????????if?(root == null) {
????????????return?false;
????????}
????????if?(root.val == sum && root.left == null?&& root.right == null) {
????????????return?true;
????????}
????????if?(root.left != null) {
????????????if?(hasPathSum(root.left, sum - root.val)) {
????????????????return?true;
????????????}
????????}
????????if?(root.right != null) {
????????????return?hasPathSum(root.right, sum - root.val);
????????}
????????return?false;
????}
}
上期推文:
