1. 程式人生 > >[Leetcode]-Path Sum

[Leetcode]-Path Sum

path subst value number tags 題目 是否 根節點 ||

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.

For example:
Given the below binary tree and sum = 22,
    5
   / \
  4  8
  /   / \
 11  13 4
 / \     \
7  2    1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Hide Tags :Tree, Depth-first Search
題目:找出二叉樹中是否有從根節點到樹葉路徑的值之和等於給定的數據sum
思路:凡是設計到二叉樹的查找,搜索…採用遞歸是一種較好的方法。
1、給出遞歸終止條件,也就是
   A:當節點為NULL時返回false
   B:當節點為樹葉(無兒子節點)時,檢查此樹葉的val是否與sum相等,相等則返回true。否則返回false
2、當不是終止條件B時。繼續向下遞歸。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool hasPathSum(struct TreeNode* root, int sum) { if(root == NULL) return false; if(root->left == NULL && root->right == NULL) return sum == root->val; return (hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val)); }
$(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); });

    [Leetcode]-Path Sum