笔试的时候碰见一个问题,当时没有解决,回来想了一下,其实也很简单……
题目要求:已知一颗树(二叉排序树),现在要求求解路径和为固定值的所有路径。
例如树:
10
5 12
4 7
所求的和为22,则输出的路径为10 5 7 以及10 12。
这个可以使用栈来暂存数据,有了这个思路之后用递归就可以解决,代码如下:
//Tencent No.4 #include <iostream> #include <vector> using namespace std; typedef class _TreeNode{ _TreeNode* pLeft; _TreeNode* pRight; _TreeNode* pFather; int data; public: _TreeNode(int value = 0):pLeft(NULL),pRight(NULL),pFather(NULL),data(value){} void Insert(_TreeNode **root,const int value); int value()const{return data;} _TreeNode *GetpLeft()const{return pLeft;} _TreeNode* GetpRight()const{return pRight;} void FindSum(_TreeNode*, int sum, int aim); }TreeNode; void TreeNode::Insert(TreeNode **root,const int value) { TreeNode *pRoot = *root; TreeNode *pParent = NULL; while (pRoot) { pParent = pRoot; if(value < pRoot->data) pRoot = pRoot->pLeft; else pRoot = pRoot->pRight; } if(!pParent) *root = new TreeNode(value); else if (pRoot == pParent->pLeft) { pParent->pLeft = new TreeNode(value); pParent->pLeft->pFather = pParent; } else { pParent->pRight = new TreeNode(value); pParent->pRight->pFather = pParent; } } void TreeNode::FindSum(TreeNode *pNode,int sum, int aim) { if(!pNode) return; if(sum + pNode->value() == aim) { vector<int>path; TreeNode *pTemp = pNode; while (pTemp) { path.push_back(pTemp->value()); pTemp = pTemp->pFather; } for (int i = path.size();i>0;--i) cout<<path[i]<<" "; cout<<endl; } else if(sum + pNode->value() < aim) { FindSum(pNode->GetpLeft(),sum + pNode->value(),aim); FindSum(pNode->GetpRight(),sum + pNode->value(),aim); } else return; } int main() { int A[] = {10,5,12,4,7}; TreeNode *root = NULL; for (int i = 0;i<5;++i) { root->Insert(&root,A[i]); } root->FindSum(root,0,22); }