劍指offer4 重建二叉樹

2021-10-04 05:14:34 字數 2059 閱讀 6318

最近全國疫情嚴重,待在家裡沒事幹,馬上又要準備春招了,最近刷刷題,記錄一下!再說一句,武漢加油,大家出門記得戴口罩!

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回根結點。

樹的遍歷有三種:分別是前序遍歷、中序遍歷、後序遍歷。本題是根據前序和中序遍歷序列重建二叉樹,我們可以通過乙個具體的例項來發現規律,不難發現:前序遍歷序列的第乙個數字就是樹的根結點。在中序遍歷序列中,可以掃瞄找到根結點的值,則左子樹的結點都位於根結點的左邊,右子樹的結點都位於根結點的右邊。

這樣,我們就通過這兩個序列找到了樹的根結點、左子樹結點和右子樹結點,接下來左右子樹的構建可以進一步通過遞迴來實現。

package com.jianzhioffer;

class

treenode

}public

class

main04

len1++

;//左子樹節點的個數++

} len2=tempin.length-len1-1;

int index1=0;

int index2=0;

int[

] tmp1=

newint

[len1]

;//當前節點的左子樹

int[

] tmp2=

newint

[len2]

;//當前節點的右子樹

boolean flag=

false

;for

(int i =

0; i < tempin.length; i++

)elseif(

!flag)

else

} treenode node=

newtreenode

((pre[index]))

; node.left=null;

node.right=null;

if(index0)

if(index0)

return node;

}public

static treenode reconstructbinarytree

(int

pre,

int[

] in)

public

static

void

main

(string[

] args)

;int

in=

; treenode root=

reconstructbinarytree

(pre,in)

;dfs1

(root)

; system.out.

println()

;dfs2

(root)

; system.out.

println()

;dfs3

(root)

; system.out.

println()

;}private

static

void

dfs1

(treenode node)

if(node.right!=null)

}private

static

void

dfs2

(treenode node)

system.out.

printf

("%d "

,node.val);if

(node.right!=null)

}private

static

void

dfs3

(treenode node)

if(node.right!=null)

system.out.

printf

("%d "

,node.val);}

}

劍指offer4 重建二叉樹

給出前序遍歷和中序遍歷,重新構建二叉樹.重建二叉樹主要就是遞迴,每一次新增乙個結點進入二叉樹,保證遞迴的順序和前序遍歷順序一致就ok了,多以左子樹的遞迴在前面,右子樹的遞迴放在後面,和前序遍歷的順序一致,第一次遞迴新增前序遍歷陣列中的第乙個,第二次遞迴新增的是前序遍歷陣列中的第二個.第n個就是陣列中...

劍指offer 4 重建二叉樹

題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。思路 中序序列中,節點左邊為左子樹,右邊為右子樹。前序第乙個為根節點 12 4 7 3 5 6 8 左 4 7 215 3...

劍指offer 4 重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。演算法設計思想 前序遍歷序列的第乙個元素為根結點的值,然後在中序遍歷序列中尋找根節點的值的位置 索引 從中序遍歷序列的起始位置到根結...