面试题34:二叉树中和为某一值的路径。输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始,往下一直到叶节点所经过的节点形成一条路径。二叉树节点定义如下:
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
遍历树中所有路径的值,把符合条件的输出:
#include <iostream>
#include <vector>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder) { //创建树
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = *startPreorder;
root->m_pLeft = root->m_pRight = nullptr;
if (startPreorder == endPreorder) { //当递归到前序遍历只含一个元素时
if (startInorder == endInorder && *startPreorder == *startInorder) { //此时若中序遍历也只含一个元素并且这个元素值与前序遍历的元素值相同时,递归到底成功返回
return root;
}
else { //否则当前序和中序遍历的个数不相等(前序遍历只含一个元素但中序遍历有多个元素)或值不相等(前序遍历和中序遍历元素数都为1但这两个值不等)时
throw exception("Invalid input."); //说明输入的前序和中序遍历不匹配
}
}
int* rootInorder = startInorder;
while (rootInorder < endInorder && *rootInorder != *startPreorder) { //遍历中序序列找到根节点
++rootInorder;
}
if (rootInorder == endInorder && *rootInorder != *startPreorder) { //若以上循环结束仍未找到根节点,说明输入有误
throw exception("Invalid input");
}
int leftLength = rootInorder - startInorder; //左子树长度
int* leftPreorderEnd = startPreorder + leftLength; //左子树尾边界
if (leftLength > 0) { //当左子树仍存在时
root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1); //继续递归左子树
}
if (leftLength < endPreorder - startPreorder) { //左子树长度小于当前遍历的树节点数-1(去掉根节点)时,说明存在右子树
root->m_pRight = ConstructCore(startPreorder + leftLength + 1, endPreorder, rootInorder + 1, endInorder); //继续递归右子树
}
return root;
}
BinaryTreeNode* Construct(int* preorder, int* inorder, int length) { //创建树
if (preorder == nullptr || inorder == nullptr || length <= 0) {
return nullptr;
}
return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector<int> path) { //形参声明为普通变量,保证对子树的路径操作不影响子树之前的路径
if (pRoot->m_nValue > expectedSum) { //递归到节点值比和还要大时,放弃这个子树
return;
}
path.push_back(pRoot->m_nValue);
if (pRoot->m_nValue == expectedSum) {
if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) {
for (int i : path) {
cout << i << " ";
}
cout << endl;
}
}
else {
expectedSum -= pRoot->m_nValue;
if (pRoot->m_pLeft != nullptr) {
FindPath(pRoot->m_pLeft, expectedSum, path);
}
if (pRoot->m_pRight != nullptr) {
FindPath(pRoot->m_pRight, expectedSum, path);
}
}
}
void FindPath(BinaryTreeNode* pRoot, int sum) {
if (pRoot == nullptr) {
return;
}
vector<int> path;
FindPath(pRoot, sum, path);
}
int main() {
int preorder[] = { 10,5,4,7,12 };
int inorder[] = { 4,5,7,10,12 };
BinaryTreeNode *pRoot = Construct(preorder, inorder, 5);
FindPath(pRoot, 22);
}