題目:輸入一棵二叉樹和一個整數,打印出二叉樹中節點值的和爲輸入整數的全部路徑。從樹的根節點開始往下一直到葉節點所通過的節點造成一條路徑。ios
如圖,輸入上圖的二叉樹和整數 22,則打印出兩條路徑,第一條路徑:10, 12; 第二條路徑爲:10, 5, 7.數據結構
因爲路徑是從根節點出發到葉節點,也就是說路徑老是以根節點爲起始點,所以首先須要遍歷根節點。在樹的前序,中序,後序三種遍歷方式中,只有前序遍歷是首先訪問根節點。函數
遍歷過程以下表:spa
分析上述過程,咱們找到了一些規律:當用前序遍歷的方式訪問到某一節點時,咱們把這個節點添加到路徑上,並累加該節點的值,若是該節點爲葉子節點而且路徑中節點值的和恰好等於輸入的整數,則當前的路徑符合要求,咱們把它打印出來。若是當前節點不是葉節點,則繼續訪問它的子節點。當前節點訪問結束後,遞歸函數將自動回到它的父節點。所以咱們在函數退出以前要在路徑上刪除當前節點,並減去當前節點的值,以確保返回父節點時路徑恰好是從根節點到父節點的路徑。不難看出保存路徑的數據結構其實是一個棧,由於路徑要與遞歸調用狀態一致,而遞歸調用的本質就是一個壓棧和出棧的過程。遞歸
//輸入一棵二叉樹和一個整數,打印二叉樹中節點值的和爲輸入整數的全部路徑
#include<iostream>
#include<vector>
using namespace std;it
typedef int ElemType;
typedef struct TNode
{
ElemType data;
struct TNode *LeftChild;
struct TNode *RightChild;
}TreeNode, *BinaryTree;io
TreeNode* BinaryTreeNode(ElemType e)
{
TreeNode *T = new TNode();
T->data = e;
T->LeftChild = NULL;
T->RightChild = NULL;
return T;
}stream
void ConnectTreeNode(TreeNode* pParent, TreeNode* pLeft, TreeNode* pRight)
{
if(pParent == NULL)
return;
pParent->LeftChild = pLeft;
pParent->RightChild = pRight;
}二叉樹
void FindTreePath(TreeNode *pRoot, int exceptionNum, vector<ElemType>& path, int currentNum)
{
currentNum += pRoot->data;
path.push_back(pRoot->data);
//若是是葉節點,而且路徑上節點的值的和等於輸入的值
//打印這條路徑
bool isLeaf = (pRoot->LeftChild == NULL) && (pRoot->RightChild == NULL);
if(currentNum == exceptionNum)
{
cout << "A path is found: ";
vector<ElemType>::iterator iter = path.begin();
for(; iter != path.end(); iter++)
{
cout << *iter << " ";
}
cout << endl;
}exception
//若是不是葉節點,則遍歷其子節點
if(pRoot->LeftChild != NULL)
FindTreePath(pRoot->LeftChild, exceptionNum, path, currentNum);
if(pRoot->RightChild != NULL)
FindTreePath(pRoot->RightChild, exceptionNum, path, currentNum);
//在返回到父節點以前,在路徑上刪除當前節點
path.pop_back();
}
void FindPath(TreeNode *pRoot, int exceptionNum)
{
if(pRoot == NULL)
return;
vector<ElemType> path;
int currentNum = 0;
FindTreePath(pRoot, exceptionNum, path, currentNum);
}
int main()
{
TreeNode *pNode1 = BinaryTreeNode(10);
TreeNode *pNode2 = BinaryTreeNode(5);
TreeNode *pNode3 = BinaryTreeNode(12);
TreeNode *pNode4 = BinaryTreeNode(4);
TreeNode *pNode5 = BinaryTreeNode(7);
ConnectTreeNode(pNode1, pNode2, pNode3);
ConnectTreeNode(pNode2, pNode4, pNode5);
int exceptionNum = 22;
FindPath(pNode1, exceptionNum);
system("pause"); return 0;}