二叉樹的遞迴遍歷

2022-08-16 22:45:14 字數 1078 閱讀 7592

遺忘 --- 真是一件迷人的事兒。 ---- 某無恥樂觀的小逗比

/**

* 題目: uva 548

* 問題描述: 給定乙個帶權(權值各不不相同,且都是小於10000的正整數)的二叉樹的中序和後序遍歷,

* 找乙個葉子使得它到樹根路徑上的權值和最小, 如果有多解, 使該葉子結點本身的權值應盡量小。

* 輸入: 第一行為中序遍歷, 第二行為後續遍歷

* 示例:

* 輸入: 7 8 11 3 5 16 12 18

* 8 3 11 7 16 18 12 5

* 輸出: 3

* * 解決方案: 遞迴建樹 ---- > dfs遍歷方案

*/

#include #include 

#include

#include

using

namespace

std;

//因為各個節點的權值各不相同且都是正整數, 直接用權值作為結點編號

const

int maxv = 10000 + 10

; int

in_order[maxv], post_order[maxv], lch[maxv], rch[maxv];

intn;

bool read_list(int *a)

//把in_order[l1..r1] 和 post_order[l2..r2]建成一棵二叉樹, 返回樹根

int build(int l1, int r1, int l2, int

r2)

int best, best_sum; //

目前為止的最優解和對應的權和

void dfs(int u, int

sum)

}if(lch[u]) dfs(lch[u], sum);

if(rch[u]) dfs(rch[u], sum);

} int

main()

return0;

}

遞迴遍歷二叉樹

include include include 二叉鍊錶表示法 typedef struct tag bitnode bitnode 先序遍歷 void xianxuorder bitnode root 先根 printf c root data 左子樹 xianxuorder root lchil...

二叉樹遞迴遍歷

編寫簡單的程式對下圖二叉樹進行遍歷 先訪問根節點 printf c root ch 再遍歷左子樹 recursion root lchild 再遍歷右子數 recursion root rchild 再遍歷左子樹 recursion root lchild 先訪問根節點 printf c root ...

二叉樹的遞迴遍歷

所謂二叉樹的遍歷,本質上就是沿某條搜尋路徑訪問樹中的每個結點,使得每個節點均被訪問一次,而且僅被訪問一次。由二叉樹的基本定義可以知道,遍歷一顆二叉樹首先必須決定對根結點 n 左子樹 l 右子樹 r 的訪問順序,按照先遍歷左孩子再遍歷右孩子的原則,常見的遍歷次序有先序遍歷 nlr 中序遍歷 lnr 和...