路径的起点为根节点,如
10
/ \
5 12
/ \
4 7 输入22,则输出10, 12和10, 5, 7两组数据。
分析:需要找到所有路径,因此需要对树进行遍历。采用前序遍历时,当前的和以及路径可以用来作为左右子树路径的基础。算法用递归实现。
#include <iostream>
using namespace std;
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
BinaryTreeNode(int value) {
m_nValue = value;
m_pLeft = m_pRight = 0;
}
};
const int MAX_PATH_LEN = 20;
int pathLength = 0;
int path[MAX_PATH_LEN];
/**
(1) sum > 0;
(2) "root" is a valid binary tree.
*/
void printPathes(int sum, BinaryTreeNode* root) {
if(pathLength > MAX_PATH_LEN) return;
path[pathLength] = root->m_nValue;
pathLength ++;
sum -= root->m_nValue;
if(sum == 0) {
for(int i = 0; i < pathLength; i++) {
cout << path[i] << " ";
}
cout << endl;
}
if(root->m_pLeft != NULL) {
printPathes(sum, root->m_pLeft);
}
if(root->m_pRight != NULL) {
printPathes(sum, root->m_pRight);
}
pathLength --;
}
int main() {
BinaryTreeNode* root = new BinaryTreeNode(10);
root->m_pLeft = new BinaryTreeNode(5);
root->m_pLeft->m_pLeft = new BinaryTreeNode(4);
root->m_pLeft->m_pRight = new BinaryTreeNode(7);
root->m_pRight = new BinaryTreeNode(12);
printPathes(22, root);
return 0;
}