1. 程式人生 > >每日一道演算法題4——在二元樹中找出和為某一值的所有路徑

每日一道演算法題4——在二元樹中找出和為某一值的所有路徑

題目:輸入一個整數和一棵二元樹。從樹的根節點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。打印出和與輸入整數相等的所有路徑。

例如輸入整數22和如下二元樹

則打印出兩條路徑:10,12和10,5,7

參考程式碼:

#include <iostream>
#include <vector>
using namespace std;

enum TREE_DIR
{
    LEFT_IN_PARRENT,
    RIGHT_IN_PARRENT
};

//定義二叉樹
struct BinaryTreeNode
{
    int m_nValue; //value of node
    BinaryTreeNode *m_pLeft; //left child of node
    BinaryTreeNode *m_pRight; //right child of node
};
BinaryTreeNode *m_pRootNode = nullptr;
int sum = 0;
vector<int> path;
int pathIndex;
void addBinaryTreeNode(BinaryTreeNode *& pCurrentNode, int value);
void orderBinaryTreeNode(BinaryTreeNode *& pCurrentNode, int SumValue, vector<int> &path);

int main(int argc, char *argv[])
{

    addBinaryTreeNode(m_pRootNode, 10);
    addBinaryTreeNode(m_pRootNode, 5); 
    addBinaryTreeNode(m_pRootNode, 12);
    addBinaryTreeNode(m_pRootNode, 7);
    addBinaryTreeNode(m_pRootNode, 4);

    orderBinaryTreeNode(m_pRootNode, 22, path);
    getchar();
    return 0;
}
//構造二叉樹
void addBinaryTreeNode(BinaryTreeNode *& pCurrentNode, int value)
{
    if (pCurrentNode == nullptr)
    {
        BinaryTreeNode *BinaryTempNode = new BinaryTreeNode;
        BinaryTempNode->m_nValue = value;
        BinaryTempNode->m_pLeft = nullptr;
        BinaryTempNode->m_pRight = nullptr;
        pCurrentNode = BinaryTempNode;
        return;
    }
    if (pCurrentNode->m_nValue > value)
    {
        addBinaryTreeNode(pCurrentNode->m_pLeft,value);
    }
    else if (pCurrentNode->m_nValue < value)
    {
        addBinaryTreeNode(pCurrentNode->m_pRight,value);
    }

} 

//遍歷二叉樹 先序遍歷 DLR
void orderBinaryTreeNode(BinaryTreeNode *& pCurrentNode,int SumValue,vector<int> &path)
{
    if (nullptr == pCurrentNode) return;

    sum += pCurrentNode->m_nValue;//每遍歷一個二叉樹結點,將其儲存值累加到sum
    path.push_back(pCurrentNode->m_nValue);//每遍歷一個二叉樹結點,將當前路徑累加到path陣列
    bool isLeaf = (nullptr == pCurrentNode->m_pLeft&&nullptr == pCurrentNode->m_pRight); //判斷是否為葉子結點
    if (isLeaf && sum == SumValue)//判斷當前所遍歷路徑是否滿足題設
    {
        pathIndex++;//滿足即將路徑數+1
        cout << "路徑"<<pathIndex<<": ";
        //滿足條件
        for (auto i : path)//列印當前路徑
        {
            cout << i << " ";
        }
        cout << endl;
    }

    orderBinaryTreeNode(pCurrentNode->m_pLeft, SumValue, path);//
    orderBinaryTreeNode(pCurrentNode->m_pRight, SumValue, path);

    path.pop_back();//不滿足刪除當前結點
    sum -= pCurrentNode->m_nValue;//刪除當前累加結點值

}

思考,如何按照中序一層一層的往二叉樹中新增元素?