题目:输入一棵二叉树和一个整数,打印出二叉树中结点值为的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:按照前序遍历的顺序遍历二叉树。将每次遍历的结点保存,然后遍历到叶结点的时候进行计算,计算完之后符合就输出,不符合就返回上一级同时删除叶结点,继续遍历。
10
5 12 从10开始遍历,10,5,4,不符合,删除4返回5。10,5,7符合,输出。删除7,返回
4 7 5,删除5,返回10。10,12符合输出。可以看出符合栈结构。
#include
#include
#include
#include
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* CreateNode(int value)
{
BinaryTreeNode* TreeNode = new BinaryTreeNode();
TreeNode->m_nValue = value;
TreeNode->m_pLeft = NULL;
TreeNode->m_pRight = NULL;
return TreeNode;
}
void ConnectTreeNodes(BinaryTreeNode* pRoot, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if (pRoot)
{
pRoot->m_pLeft = pLeft;
pRoot->m_pRight = pRight;
}
}
//销毁树
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != NULL)
{
delete pRoot;
pRoot = NULL;
DestroyTree(pRoot->m_pLeft);
DestroyTree(pRoot->m_pRight);
}
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector& path, int& currentSum);
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
if (pRoot == NULL)
{
return;
}
vector path;
int currentSum = 0;
FindPath(pRoot, expectedSum, path, currentSum);
}
void FindPath
(
BinaryTreeNode* pRoot,
int expectedSum,
vector& path,
int currentSum
)
{
currentSum += pRoot->m_nValue;
path.push_back(pRoot->m_nValue);
//如果是叶结点,并且路径上结点的和等于输入的值,打印这条路径
bool isLeaf = pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL;
if (currentSum == expectedSum && isLeaf)
{
vector::iterator iter = path.begin();
for (; iter != path.end(); iter++)
{
cout << iter << " ";
}
cout << 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();
}
void test()
{
BinaryTreeNode* node1 = CreateNode(10);
BinaryTreeNode* node2 = CreateNode(5);
BinaryTreeNode* node3 = CreateNode(12);
BinaryTreeNode* node4 = CreateNode(4);
BinaryTreeNode* node5 = CreateNode(7);
ConnectTreeNodes(node1, node2, node3);
ConnectTreeNodes(node2,node4,node5);
FindPath(node1, 22);
DestroyTree(node1);
}
int main()
{
test();
return 0;
}