Fork me on GitHub

112. Path Sum

欢迎fork and star:Nowcoder-Repository-github

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

解析

class Solution_112 {
public:
	bool dfs(TreeNode* root, int cur_sum, int sum)
	{
		if (!root)
		{
			return false;
		}
		cur_sum += root->val;
		if (root->left == NULL&&root->right == NULL&&cur_sum == sum)
		{
			return true;
		}

		return dfs(root->left, cur_sum, sum) || dfs(root->right, cur_sum, sum);
	}

	bool hasPathSum(TreeNode *root, int sum) {
		if (!root)
		{
			return false;
		}
		return dfs(root, 0, sum);
	}


	bool hasPathSum1(TreeNode* root, int sum) { //递归
		if (root == nullptr){
			return false;
		}
		else if (root->left == nullptr && root->right == nullptr && root->val == sum){
			return true;
		}
		else{
			return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
		}
	}
	bool hasPathSum2(TreeNode *root, int sum) { //dfs

		//用非递归的先序和后序遍历感觉都有问题,需要额外的辅助变量才行
		if (!root)
		{
			return false;
		}
		stack<TreeNode*> sta;
		int ret = 0;

		TreeNode* p = root;
		TreeNode* temp;
		TreeNode* preNode;
		while (p!=NULL||!sta.empty())
		{
			while (p!=NULL)
			{
				sta.push(p);
				ret += p->val;
				p = p->left;
				if (p->left==NULL&&p->right==NULL)
				{
					if (ret==sum)
					{
						return true;
					}
				}
			}
			if (!sta.empty())
			{
				temp = sta.top(); //减有bug 
				if (temp->right&&preNode!=temp) //右孩子还未访问
				{
					p = p->right;  //到外层while
				}
				else
				{
					preNode = p;
					sta.pop();
					ret -= temp->val;
				}
			}
		}

		return false;
	}

	bool hasPathSum3(TreeNode* root, int sum) { //bfs
		if (!root)
		{
			return false;
		}

		queue<TreeNode*> que;
		queue<int> sum_que;
		que.push(root);
		sum_que.push(root->val);

		while (!que.empty())
		{
			TreeNode* cur = que.front();
			que.pop();
			int ret = sum_que.front();
			sum_que.pop();

			if (cur->left==NULL&&cur->right==NULL&&ret==sum)
			{
				return true;
			}
			if (cur->left)
			{
				que.push(cur->left);
				sum_que.push(ret + cur->left->val);
			}
			if (cur->right)
			{
				que.push(cur->right);
				sum_que.push(ret + cur->right->val);
			}
		}
		return false;

	}
};

题目来源

posted @ 2018-01-07 17:13  ranjiewen  阅读(181)  评论(0编辑  收藏  举报