二叉樹中和爲某一值的路徑

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

struct BinaryTreeNode{
	int m_value;
	BinaryTreeNode* m_pleft;
	BinaryTreeNode* m_pright;
}; 

void find(BinaryTreeNode* pRoot,int expectedsum){
	if(pRoot == NULL) return ;
	vector<int> path;
	int currentsum = 0;
	findpath(pRoot,expectedsum,path,currentsum);
}

//pRoot根節點, expectedsum希望得到的和,path 爲雙重堆棧,currentsum爲當前路徑的和 
void findpath(BinaryTreeNode* pRoot,int expectedsum,vector<int> &path,int currentsum){
	 currentsum +=pRoot->m_value;
	 path.push_back(pRoot->m_value);
	 
	//如果當前節點爲葉節點 
	if(pRoot->m_pleft==NULL&&pRoot->m_pright==NULL&¤tsum == expectedsum){
		//打印路徑 
		vector<int>::iterator iter = path.begin();//iterator迭代器 
		while(iter!=path.end()){
			cout<<*iter<<endl;
		} 
	}
	
	//如果不是葉節點
	if(pRoot->m_pleft!=NULL) Findpath(pRoot->m_pleft,expectedsum,path,currentsum); 
	if(pRoot->m_pright!=NULL) Findpath(pRoot->m_pright,expectedsum,path,currentsum); 
	
	//刪除該路徑上的節點
	path.pop_back(); 
}

發佈了93 篇原創文章 · 獲贊 6 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章