五:二叉树中和为某一直的路径
比如:求和為22的路徑
求值步驟
規律:當用前序遍歷的方式訪問到某一節點時,我們把這個節點加入到路徑上,并累加該節點的值,假設該節點為葉子節點而且路徑中節點值的和剛好等于輸入的整數。則當前的路徑符合要求。我們把它打印出來。假設當前節點不是葉節點。則繼續訪問它的子節點。
當前節點訪問結束后。遞歸函數將自己主動回到它的父節點。
因此我們在函數退出之前要在路徑上刪除當前節點。并減去當前節點的值,以確保返回父節點時路徑剛好是從根節點到父節點的路徑。不難看出保存路徑的數據結構實際上是一個棧,由于路徑要與遞歸調用狀態一致,而遞歸調用的本質就是一個壓棧和出棧的過程。
可是因為使用棧不便于路徑的輸出,所以能夠借助于vector的push_back和pop_back在尾部增刪路徑節點,實現棧的功能。
voidFindPath
(
??? BinaryTreeNode*?? pRoot,???????
??? int?????????????? expectedSum,?
??? std::vector<int>& 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 == expectedSum &&isLeaf)
??? {
??????? printf("A path is found: ");
???????std::vector<int>::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);
?
??? //在返回到父結點之前。在路徑上刪除當前結點。
??? //并在currentSum中減去當前結點的值
??? currentSum -= pRoot->m_nValue;
??? path.pop_back();
}
?
voidCallFindPath(BinaryTreeNode* pRoot, int expectedSum)
{
??? if(pRoot == NULL)
??????? return;
?
??? std::vector<int> path;
??? int currentSum = 0;
??? FindPath(pRoot, expectedSum, path,currentSum);
}
總結
以上是生活随笔為你收集整理的五:二叉树中和为某一直的路径的全部內容,希望文章能夠幫你解決所遇到的問題。