在二叉樹中找出和為某一值的所有路徑


題目:輸入一個整數和一棵二元樹。
從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。
打印出和與輸入整數相等的所有路徑。
例如 輸入整數22和如下二元樹
      10   
      / \  
     5  12   
      / \   
      4    7
則打印出兩條路徑:10, 12和10, 5, 7。


先序遍歷樹即可得到結果。

算法: PrintPath(TreeNode* pRoot, int sum, const int target)  用來計算,sum為棧中的元素的和,target為目標值。

到達一個節點之后計算當前節點和sum的和,如果為target,輸出路徑返回,如果大於target,則直接返回,如果小於,則將當前節點的值入棧,更新sum的值,繼續遍歷,遍歷完成之后,也就是從當前節點返回的時候,將其從棧中彈出,更新sum。
代碼如下:

#include "stdafx.h"
#include <iostream>
#include <deque>
using namespace std;

struct TreeNode
{
    int data;
    TreeNode* pLeftChild;
    TreeNode* pRightChild;
};

void CreateTree(TreeNode*& pRoot)
{
    char buffer[10];  
    memset(buffer, 0, 10);  
    std::cin.getline(buffer, 9);  
    int a = atoi(buffer);  
    if(a == 0) pRoot = NULL;  
    else  
    {  
        pRoot = new TreeNode();  
        pRoot->data = a;  
        pRoot->pLeftChild = pRoot->pRightChild = NULL;  
        CreateTree(pRoot->pLeftChild);  
        CreateTree(pRoot->pRightChild);  
    }  
}

void PrintPath(TreeNode* pRoot, int sum, const int target)  
{
    static deque<int> stack;  

    if(pRoot == NULL)    return;
    if(sum + pRoot->data == target)// 如果當前值加上路徑和為目標值,則輸出
    {
        for(int i=0; i<stack.size(); i++)
            cout<<stack[i]<<"->";
        cout<<pRoot->data<<endl;
        return;
    }
    else if(sum + pRoot->data > target)//如果大於目標值,則返回
    {
         return;
    }
    else// 如果小於,則入棧
    {
        stack.push_back(pRoot->data);
        sum += pRoot->data;
        PrintPath(pRoot->pLeftChild, sum, target);
        PrintPath(pRoot->pRightChild,sum,target);
        sum -= pRoot->data;
        stack.pop_back();
    }

}

int main()
{
     TreeNode* pTree = NULL;  
    CreateTree(pTree); 
    PrintPath(pTree, 0, 22);  

}

輸入輸出的結果如下:

10
5
4
#
#
7
#
#
12
#
#


10->5->7
10->12

前一半為輸入,之后為輸出。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM