題目
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.
解題之法
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL && root->val == sum ) return true;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
分析
這道求二叉樹的路徑需要用深度優(yōu)先算法DFS的思想來遍歷每一條完整的路徑,也就是利用遞歸不停找子節(jié)點的左右子節(jié)點,而調(diào)用遞歸函數(shù)的參數(shù)只有當前節(jié)點和sum值。
首先,如果輸入的是一個空節(jié)點,則直接返回false;如果如果輸入的只有一個根節(jié)點,則比較當前根節(jié)點的值和參數(shù)sum值是否相同,若相同,返回true,否則false。
這個條件也是遞歸的終止條件。
下面我們就要開始遞歸了,由于函數(shù)的返回值是Ture/False,我們可以同時兩個方向一起遞歸,中間用或||連接,只要有一個是True,整個結果就是True。遞歸左右節(jié)點時,這時候的sum值應該是原sum值減去當前節(jié)點的值。