find all pairs of elements in a balanced BST that sum to a certain number
生活随笔
收集整理的這篇文章主要介紹了
find all pairs of elements in a balanced BST that sum to a certain number
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a??number. find all pairs of elements in a balanced bst,?
which sum to this number. Make sure you don't return same pair again
我的想法是先序遍歷每個節點,然后在每個節點處調用查找函數
但是這有問題,給定數8, 之前查到的節點是1,7; 后來查到的節點是7,1
像這類題目,需要避免重復,就要考慮到順序。
用中序遍歷樹,這樣就可以保證節點從小到大遞增,在查找時要判斷是否小于given number/2
struct NODE {int nVal;NODE* pLft;NODE* pRgt;NODE(int n) : nVal(n), pLft(NULL), pRgt(NULL) {} };NODE* GetPair(int nSum, NODE* pRoot, NODE* pCur) {assert(pRoot != NULL && pCur != NULL);if (nSum - pCur->nVal <= pCur->nVal) return NULL;NODE* pRes = pRoot;while (NULL != pRes){if (pRes->nVal == nSum - pCur->nVal)break;if (pRes->nVal < nSum - pCur->nVal)pRes = pRes->pRgt;elsepRes = pRes->pLft;}return pRes; }void GetPairsToSum(int nSum, NODE* pRoot, NODE* pCur, vector<pair<NODE*, NODE*>>& vec) {if (NULL == pCur || NULL == pRoot) return;GetPairsToSum(nSum, pRoot, pCur->pLft, vec);NODE* pRes = GetPair(nSum, pRoot, pCur);if (NULL != pRes)vec.push_back(make_pair(pCur, pRes));GetPairsToSum(nSum, pRoot, pCur->pRgt, vec); }
總結
以上是生活随笔為你收集整理的find all pairs of elements in a balanced BST that sum to a certain number的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 相同bit1的最大的数
- 下一篇: 从三个数组中选择满足条件的三个数