二叉樹的路徑和---遞歸返回時要彈出向量尾的元素,不管是否找到。

給定一個二叉樹,找出所有路徑中各節點相加總和等於給定 目標值的路徑。

一個有效的路徑,指的是從根節點到葉節點的路徑。

http://www.lintcode.com/zh-cn/problem/binary-tree-path-sum/

樣例

給定一個二叉樹,和 目標值 = 5:

     1
    / \
   2   4
  / \
 2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]
#include <iostream>
#include <vector>
#include <string>
#include <sstream> 
#include <stack> 
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
using namespace std;

class TreeNode {
public:
	int val;
	TreeNode *left, *right;
	TreeNode(int val) {
		this->val = val;
		this->left = this->right = NULL;
	}
};

void process(TreeNode *root, int target,vector<vector<int>>&  resvv,vector<int>& v,int sum){
	if(root == NULL) return;
	if(root->left == NULL && root->right == NULL ){//葉子結點
		if(sum+ root->val == target){ //找到了,加入resvv
			v.push_back(root->val);
			resvv.push_back(v);
			v.pop_back();
		}
		return;//到了葉子就要返回
	}
	v.push_back(root->val);
	sum += root->val;
	process(root->left, target,resvv,v,sum);
	process(root->right, target,resvv,v,sum);
	if(v.size() != 0)  v.pop_back();//返回時要彈出 最後的元素,不管是否找到。

}

vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
	vector<vector<int>>  resvv;
	if(root == NULL) return resvv;

	vector<int> v;
	int sum=0;
	process(root,target,resvv,v,sum);

	return resvv;
}

int  main(){
	TreeNode* root=new TreeNode(1);//test1
	root->left=new TreeNode(2);
	root->left->left=new TreeNode(3);

	TreeNode* root2=new TreeNode(1);//test2
	root2->left=new TreeNode(2);
	root2->right=new TreeNode(4);

	root2->left->left=new TreeNode(2);
	root2->left->right=new TreeNode(5);
	binaryTreePathSum(root2,5);
	cout<< "maxPathSum(root)="<<endl;
	system("pause");
}

注意:if(v.size() != 0)  v.pop_back();//返回時要彈出 最後的元素,不管是否找到。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章