题目描述:输入一颗二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
二叉树结点定义:
//二叉树定义
struct BinTreeNode{
int m_value;
BinTreeNode *left;
BinTreeNode *right;
//创建根节点,值为e
BinTreeNode* createRoot(int e);
//将e作为当前结点的左孩子值插入
void insertAsLC(int e);
//将e作为当前结点的右孩子值插入
void insertAsRC(int e);
};
解题思路:
- 首先要明白,路径指的是以根节点为起点至叶节点。
- 由于以根为起始点,所以我们需要用到前序遍历。
- 把经过的路径上的节点保存下来。每访问到一个节点的时候,我们都把当前的节点添加到路径中去。
- 到叶节点时计算值。
- 再遍历其他节点,遍历下一节点前要回溯。
- 回溯时删除当前结点并减去当前节点值。
测试用例:
int main(){
//创建一颗二叉树
BinTreeNode *tree = new BinTreeNode;
tree->m_value = 8;
BinTreeNode *tree2 = new BinTreeNode;
tree2 = NULL;
tree->insertAsLC(6); //左孩子为6
tree->insertAsRC(10);
tree->left->insertAsLC(5);
tree->left->insertAsRC(7);
tree->right->insertAsLC(1);
tree->right->insertAsRC(11);
//寻找是否存在值为19的路径
FindPath(tree, 19); //Output: A path is found: 8 6 5和A path is found: 8 10 1
return 0;
}
函数实现:
//辅助函数,核心过程
void FindPath(BinTreeNode *pRoot, int expectedSum, std::vector<int> &path, int currentSum){
//根节点值
currentSum += pRoot->m_value;
//根节点入向量
path.push_back(pRoot->m_value);
//递归基,如果是叶节点并且路径上的节点的和等于输入的值
bool isLeaf = pRoot->left == NULL && pRoot->right == NULL;
if(currentSum == expectedSum && isLeaf){
//那么打印路径
std::cout << "A path is found: ";
std::vector<int>::iterator iter = path.begin();
for(; iter != path.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
}
//如果不是叶节点,则遍历它的子节点
if(pRoot->left != NULL)
FindPath(pRoot->left, expectedSum, path, currentSum);
if(pRoot->right != NULL)
FindPath(pRoot->right, expectedSum, path, currentSum);
//在返回父节点之前,在路径上删除当前结点
path.pop_back();
}
//主函数
void FindPath(BinTreeNode *pRoot, int expectedSum){
if(pRoot == NULL)
return;
//使用向量保存路径
std::vector<int> path;
//当前和
int currentSum = 0;
//核心函数
FindPath(pRoot, expectedSum, path, currentSum);
}
其他函数:
//其他函数实现
//创建根节点,值为e
BinTreeNode* BinTreeNode::createRoot(int e){
BinTreeNode *root = new BinTreeNode;
root->m_value = e;
return root;
}
//作为节点的左孩子插入元素e
void BinTreeNode::insertAsLC(int e){
BinTreeNode *Left = new BinTreeNode;
Left->m_value = e;
this->left = Left;
}
//作为节点的右孩子插入元素e
void BinTreeNode::insertAsRC(int e){
BinTreeNode *Right = new BinTreeNode;
Right->m_value = e;
this->right = Right;
}