java 二叉树中和为某一值的路径_25. 二叉树中和为某一值的路径
題目:輸入一棵二叉樹和一個整數,打印出二叉樹中結點值為的和為輸入整數的所有路徑。從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。
思路:按照前序遍歷的順序遍歷二叉樹。將每次遍歷的結點保存,然后遍歷到葉結點的時候進行計算,計算完之后符合就輸出,不符合就返回上一級同時刪除葉結點,繼續遍歷。
10
5??? 12???? 從10開始遍歷,10,5,4,不符合,刪除4返回5。10,5,7符合,輸出。刪除7,返回
4?? 7???????? 5,刪除5,返回10。10,12符合輸出。可以看出符合棧結構。
#include
#include
#include
#include
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* CreateNode(int value)
{
BinaryTreeNode* TreeNode = new BinaryTreeNode();
TreeNode->m_nValue = value;
TreeNode->m_pLeft = NULL;
TreeNode->m_pRight = NULL;
return TreeNode;
}
void ConnectTreeNodes(BinaryTreeNode* pRoot, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if (pRoot)
{
pRoot->m_pLeft = pLeft;
pRoot->m_pRight = pRight;
}
}
//銷毀樹
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != NULL)
{
delete pRoot;
pRoot = NULL;
DestroyTree(pRoot->m_pLeft);
DestroyTree(pRoot->m_pRight);
}
}
void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector& path, int& currentSum);
void FindPath(BinaryTreeNode* pRoot, int expectedSum)
{
if (pRoot == NULL)
{
return;
}
vector path;
int currentSum = 0;
FindPath(pRoot, expectedSum, path, currentSum);
}
void FindPath
(
BinaryTreeNode* pRoot,
int expectedSum,
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 == expectedSum && isLeaf)
{
vector::iterator iter = path.begin();
for (; iter != path.end(); iter++)
{
cout << iter << " ";
}
cout << endl;
}
//如果不是葉結點,則遍歷它的子結點
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();
}
void test()
{
BinaryTreeNode* node1 = CreateNode(10);
BinaryTreeNode* node2 = CreateNode(5);
BinaryTreeNode* node3 = CreateNode(12);
BinaryTreeNode* node4 = CreateNode(4);
BinaryTreeNode* node5 = CreateNode(7);
ConnectTreeNodes(node1, node2, node3);
ConnectTreeNodes(node2,node4,node5);
FindPath(node1, 22);
DestroyTree(node1);
}
int main()
{
test();
return 0;
}
總結
以上是生活随笔為你收集整理的java 二叉树中和为某一值的路径_25. 二叉树中和为某一值的路径的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 啤酒一瓶多少钱啊?
- 下一篇: java中json重复数据结构_JS实现