码迷,mamicode.com
首页 > 其他好文 > 详细

Path Sum(LeetCode)

时间:2015-03-30 13:24:31      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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.

程序代码如下:

#include<iostream>
#include<queue>
#include<vector>
using namespace std;

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;
		//类似先序遍历,首先访问根节点
		treeNodeVec.push_back(root);
		//判断是否到路径终点
		if(root->left==NULL && root->right==NULL){
			int tempSum=0;
			for(vector<TreeNode*>::iterator iter=treeNodeVec.begin();iter!=treeNodeVec.end();++iter){
				tempSum+=(*iter)->val;
			}
			if(sum==tempSum)
				return true;
			else{
				treeNodeVec.pop_back();//叶子节点回溯操作
				return false;
			}
		}

		bool lflag=false,rflag=false; //递归判断左右子树是否为true
		//如果存在左子树则判断,否则为false
		if(root->left!=NULL)
			lflag=hasPathSum(root->left,sum);
		if(!lflag && root->right!=NULL) //如果左子树为true,则停止判断右子树
			rflag=hasPathSum(root->right,sum);
		treeNodeVec.pop_back(); //非叶节点回溯,最后vec为空
		return  lflag || rflag;
	}
public:
	vector<TreeNode*> treeNodeVec;
};
int main(){
	TreeNode node1(1);
	TreeNode node2(2);
	node1.left=&node2;
	Solution solution;
	cout<<solution.hasPathSum(&node1,0)<<endl;
	return 0;

}

Path Sum(LeetCode)

标签:

原文地址:http://blog.csdn.net/sxhlovehmm/article/details/44748869

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!