重建二叉樹

2021-06-09 13:38:23 字數 897 閱讀 3347

摘自劉汝佳的《演算法競賽入門經典》

preorder(t) =  t 的根結點 + preorder(t 的左子樹) + preorder(t 的右子樹);

inorder(t) =  inorder(t 的左子樹) + t 的根結點 + inorder(t 的右子樹);

postorder(t) =  postorder(t 的左子樹) +  postorder(t 的右子樹) + t 的根結點;

輸入一顆二叉樹的先序遍歷和中序遍歷,輸出它的後序遍歷。

sample input

dbacegf abcdefg

bcad cbad

sample output

acbfged

cdab

#include

<

stdio.h

>

#include

<

string

.h>

void

build(

intn,

char

*s1,

char

*s2,

char*s)

intmain()

}

也可以省略build()函式的最後乙個引數;

#include

<

stdio.h

>

#include

<

string

.h>

void

build(

intn,

char

*s1,

char

*s2)

intmain()

}

二叉樹 重建二叉樹

問題 給定二叉樹的前序遍歷結果和中序遍歷結果,恢復出原二叉樹。假設二叉樹中的元素都不重複,給定二叉樹的前序遍歷序列,二叉樹的中序遍歷序列。看到此題,我首先想到的是尋找根節點,由前序遍歷序列可以看出根節點為1,此時通過中序遍歷可以看出來4,7,2在根節點的左子樹,5,3,8,6在樹的右節點。此時我們可...

二叉樹 重建二叉樹

題目給定兩個陣列,乙個是前序遍歷陣列 preorder 乙個是中序遍歷陣列 inorder 要求輸出還原二叉樹 核心在於我們要理解前序和中序便利的特點 前序遍歷 根節點 左節點 右節點 中序遍歷 左節點 根節點 右節點 所以我們從二叉樹的根節點開始重構 也就是preorder的第乙個值 同時用乙個m...

二叉樹重建

摘自劉汝佳的 演算法競賽入門經典 preorder t t 的根結點 preorder t 的左子樹 preorder t 的右子樹 inorder t inorder t 的左子樹 t 的根結點 inorder t 的右子樹 postorder t postorder t 的左子樹 postord...