问题分析:核心是树的遍历,注意题目中“路径”的定义,是从根节点到叶子节点。先序遍历正好是从根节点开始,因此可以利用先序遍历的过程来实现这个过程。
方法:
void print_vector(vector<BinaryTreeNode *> &v){
vector<BinaryTreeNode *>::iterator it;
for (it = v.begin(); it != v.end(); it ++){
printf("%d\t", (*it)->m_nValue);
}
printf("\n");
}
void pre_order_route(BinaryTreeNode *p, int num, vector<BinaryTreeNode *> &q, int ¤t){
if (NULL == p) return;
current += p->m_nValue;
q.push_back(p);
bool is_leaf = (NULL == p->m_pLeft) && (NULL == p->m_pRight);
if (current == num && is_leaf){
print_vector(q);
}
if (NULL != p->m_pLeft){
pre_order_route(p->m_pLeft, num, q, current);
}
if (NULL != p->m_pRight){
pre_order_route(p->m_pRight, num, q, current);
}
current -= (*(q.end() - 1))->m_nValue;
q.pop_back();
}
void print_route(BinaryTreeNode *root, int num){
vector<BinaryTreeNode *> q;// 用队列保存已经访问过的节点
int current = 0;
pre_order_route(root, num, q, current);
}