题目:输入一二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶子结点所经过的结点形成一条路径。二叉树的定义如下:
struct BinaryTreeNode{ int m_nVlaue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight;};
分析:对二叉树进行前序遍历,并利用递归来进行回溯到父节点的情况。实现如下:
void FindPath(BinartTreeNode* pRoot,int expectedSum){ if(pRoot==NULL) return; std::vector path; int currentSum=0; FindPath(pRoot,expectedSum,path,currentSum);}void FindPath(BinaryTreeNode* pRoot,int expectedSum,std::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==exceptedSum&&isLeaf) { printf("A path is found: "); std::vector ::iterator iter=path.begin(); for(;iter!=path.end();++iter) printf("%d\t",*iter); printf("\n"); } 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();}