`
bcyy
  • 浏览: 1825572 次
文章分类
社区版块
存档分类
最新评论

LeetCode Path Sum 路径和

 
阅读更多

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 andsum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

检查一颗二叉树是否有和某数相等的路径。和前面的最少深度二叉树思路差不多。

1 每进入一层,如果该层跟节点不为空,那么就加上这个值。

2 如果到了叶子节点,那么就与这个特定数比较,相等就说明存在这样的路径。

当然可以不是用递归优化一点算法吧。是用循环的话就可以在找到值的时候直接返回。递归也可以增加判断,找到的时候每层加判断迅速返回,不过感觉效果也高不了多少。

/**
 * 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) {
		bool judge = false;
		minD(root, sum, judge);
		return judge;
	}

	void minD(TreeNode *node, int overall, bool& judge, int levelNum = 0)
	{
		if(node == nullptr) return;
		levelNum += node->val;
		minD(node->left, overall,judge, levelNum);
		minD(node->right, overall,judge, levelNum);
		if(node->left==nullptr && node->right==nullptr && overall==levelNum)
			judge = true;
	}
};


//2014-2-17 update
	bool hasPathSum(TreeNode *root, int sum) 
	{
		if (!root) return false;
		if (!root->left && !root->right && root->val == sum) return true;
		if (hasPathSum(root->left, sum - root->val) 
			|| hasPathSum(root->right, sum - root->val)) return true;
	}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics