【經典資料結構演算法】(4)二叉樹求和為定值的所有路徑

來源:互聯網
上載者:User
 1 /*
2 題目:輸入一個整數和一顆二叉樹。
3 從樹的根結點開始往下訪問一直到葉結點所經過的所有結點形成一條路徑。
4 列印出與輸入整數相等的所有路徑。
5 例如 輸入整數22和如下二元樹
6 10
7 / \
8 5 12
9 / \
10 4 7
11 則列印出兩條路徑:10,12和12,5,7
12 分析:
13 在二叉樹中尋找滿足條件的所有結點序列,需要輸出所有的序列。
14 此時,很自然的就應該想到使用棧這樣的資料結構。
15 訪問結點為一個函數,在進入這個函數的時候,首先把要訪問的結點壓入棧中。
16 計算此時所有的路徑長度,如果滿足指定的條件,則輸出序列。
17 如果存在子節點的時候,就需要遞迴調用該函數訪問子節點。
18 最後在退出函數的時候,記得要將當前結點從棧中彈出。
19 總體的思想即是如此,下面為具體實現。
20 */
21
22 #include "stdafx.h"
23 #include <stdlib.h>
24 //二叉樹的定義
25 typedef struct BinaryTreeNode
26 {
27 int m_nValue;
28 BinaryTreeNode *m_pLeft;
29 BinaryTreeNode *m_pRight;
30 }BinaryTreeNode,*pBinaryTreeNode;
31
32 //初始化結點
33 pBinaryTreeNode initNode(int value)
34 {
35 pBinaryTreeNode node=(pBinaryTreeNode)malloc(sizeof(BinaryTreeNode));
36 node->m_nValue=value;
37 node->m_pLeft=NULL;
38 node->m_pRight=NULL;
39 return node;
40 }
41
42 //定義一個棧結構,假定棧的最大空間為100
43 pBinaryTreeNode base[100];
44
45 //定義棧頂
46 int top=0;
47
48 //所求的路徑長度
49 int target=22;
50
51 int i,sum;
52 void visit(pBinaryTreeNode root)
53 {
54 //將要訪問的結點入棧
55 base[top]=root;
56 top++;
57
58 //計算當前值是否是所要求的路徑長度
59 for(i=0,sum=0;i<top;i++)
60 {
61 sum+=base[i]->m_nValue;
62 }
63 if(sum==target)
64 {
65 //輸出路徑
66 printf("路徑符合要求:\n");
67 for(i=0;i<top;i++)
68 {
69 printf("%d\t",base[i]->m_nValue);
70 }
71 printf("\n");
72 }
73 //如果存在子結點,則訪問
74 if(root->m_pLeft)
75 visit(root->m_pLeft);
76 if(root->m_pRight)
77 visit(root->m_pRight);
78
79 //出棧當前結點
80 top--;
81 }
82 int _tmain(int argc, _TCHAR* argv[])
83 {
84 //構造一顆二叉樹,如同題目中的二叉樹
85 pBinaryTreeNode root=initNode(10);
86 root->m_pLeft=initNode(5);
87 root->m_pRight=initNode(12);
88 root->m_pLeft->m_pLeft=initNode(4);
89 root->m_pLeft->m_pRight=initNode(7);
90
91 visit(root);
92 return 0;
93 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.