二叉樹的構建和遍歷(例題)

2021-10-19 14:41:16 字數 1292 閱讀 4981

直接進入正題:

比如有些題目給你一顆二叉樹的前序遍歷和中序遍歷,然後讓你求層序遍歷或者後序遍歷。

這種題目的基本思路有兩個:

1.給定的序列是以字串的形式:

比如後序序列:bdca,中序序列:badc ,然後讓你求先序序列。

這類問題實際上已經為你構建好了數,只需要利用字串的擷取操作(sunstr)以及dfs / bfs解決:

參考文章

<==戳這

#include

#include

#include

using

namespace std;

==>要注意在樹的每一部分,任何型別的遍歷序列長度都是一樣的

void

dfs(string mid,string post)

}int

main()

2.給定的序列是整形,需要陣列儲存:

後序序列:2 3 1 5 7 6 4

中序序列:1 2 3 4 5 6 7

然後讓你求前序序列。這類問題需要構建這顆二叉樹,然後再根據題意運用 dfs / bfs 解決。

比如這道題:求層序序列 就運用了bfs

#include

#include

#include

using

namespace std;

int post[50]

,inor[50]

,n;//後序序列,中序序列,個數

struct node

;node*

tree

(int postl,

int postr,

int inl,

int inr)

}int numleft=k-inl;

//左子樹的結點個數

//二叉樹結點的建立是從左到右的

//更改下標繼續建樹(仔細)

root-

>lchild =

tree

(postl,postl+numleft-

1,inl,k-1)

; root-

>rchild =

tree

(postl+numleft,postr-

1,k+

1,inr)

;return root;

}int num=0;

void

bfs(node* root)

}int

main()

構建二叉樹 遍歷二叉樹

陣列法構建二叉樹 public class main public static void main string args 用陣列的方式構建二叉樹 public static void createbintree 把linkedlist集合轉成二叉樹的形式 for int j 0 j 最後乙個父節...

二叉樹建立和遍歷

二叉樹建立遍歷規則 1.先序 根 左 右 2.中序 左 根 右 3.後序 左 右 根 二叉樹定義和輔助函式如下 struct node void visit int data int indata 先序建立二叉樹 struct node createbitree 先序建立乙個二叉樹 return t...

二叉樹建立和遍歷

include include 帶返回值建立二叉樹 最簡單方法 節點資料結構 struct bs node typedef struct bs node tree tree head,p,root 建立二元查詢樹 有返回值的可以不傳參 沒有的話如何傳參 輸入0代表到了某個葉子節點 tree crea...