LeetCode | 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.

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.

思路:本題意思是在二叉樹中是否存在一條路徑,該路徑上的元素值總和爲已知給出的sum。

因此,實際上可以將每層的結點值做一個轉化,例如上述例子中第二層的結點值爲4,8,那麼到達第二層時,實際路徑上的元素值和是5+4,5+8。即9,13.

所以,可以採用這種方法,逐層地下去,直到葉子節點。判斷葉子結點值是否與sum相等即可。在程序中可以用遞歸的思路實現。

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) 
	{
		if(!root)
			return false;
		else
			return PathSum(root,0,sum);
    }
	bool PathSum(TreeNode* p, int total, int sum)
	{
		if(!p->left && !p->right)
			return sum == total + p->val;
		else if(p->left && !p->right)
			return PathSum(p->left, total+p->val, sum);
		else if(p->right && !p->left)
			return PathSum(p->right, total+p->val, sum);
		else
			return (PathSum(p->left, total+p->val, sum) || PathSum(p->right, total+p->val, sum));
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章