LeetCode112.路径总和

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

          5

         / \

        4   8

       /    /  \

     11  13  4

    /  \      \

   7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

#include <iostream>
#include <queue>
#include<vector>
#include <cstdlib>
#include <cstring>
#include<algorithm>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(NULL), right(NULL) {}
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

/*
层次遍历的时候将一层的结点值加入到一个vector中,再将这个vector加入结果中
最后逆置结果即可 
*/
class Solution{
	vector<vector<int> > result;
	vector<int> path;
public:
	bool hasPathSum(TreeNode* root,int sum) {
		int path_value = 0;
		preorder(root,sum,path_value);
		return result.size() > 0 ? true : false;
    }
    void preorder(TreeNode *node,int sum,int &path_value) {
    	if(!node) {
    		return;
		}
		if(result.size() > 0) { //已经有一个路径满足条件了,无需再判断后面的路径 
			return;
		}
		path_value += node->val;
		path.push_back(node->val);
		if(!node->left && !node->right && path_value == sum) {
			result.push_back(path);
		}
		preorder(node->left,sum,path_value);
		preorder(node->right,sum,path_value);
		path_value -= node->val;
		path.pop_back();
	}
};

TreeNode* inputTree()
{
    int n,count=0;
    char item[100];
    cin>>n;
    if (n==0)
        return NULL;
    cin>>item;
    TreeNode* root = new TreeNode(atoi(item));
    count++;
    queue<TreeNode*> nodeQueue;
    nodeQueue.push(root);
    while (count<n)
    {
        TreeNode* node = nodeQueue.front();
        nodeQueue.pop();
        cin>>item;
        count++;
        if (strcmp(item,"null")!=0)
        {
            int leftNumber = atoi(item);
            node->left = new TreeNode(leftNumber);
            nodeQueue.push(node->left);
        }
        if (count==n)
            break;
        cin>>item;
        count++;
        if (strcmp(item,"null")!=0)
        {
            int rightNumber = atoi(item);
            node->right = new TreeNode(rightNumber);
            nodeQueue.push(node->right);
        }
    }
    return root;
}

int main()
{
	TreeNode* root;
	root=inputTree();
	int sum;
    cin>>sum;
    bool res=Solution().hasPathSum(root,sum);
    cout<<(res?"true":"false");
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值