題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。
題解:
已知前序遍歷和中序遍歷求二叉樹。
我們需要找到前序遍歷陣列pre和中序遍歷陣列in確定二叉樹的規律。
根據前序遍歷的性質,我們可以從pre[0]知道節點1是該樹的根節點,然後在in中找到節點1,根據中序遍歷的性質,我們可以知道in[0] ~ in[2]是該樹的左子樹,in[4] ~ in[7]是該樹的右子樹。接下從pre[1]可以知道節點2是子樹in[0] ~ in[2]的根節點,從in中找到節點2,我們可以知道in[0] ~ in[1]是子樹in[0] ~ in[2]的左子樹,而且它沒有右子樹,可以發現,這個做法可以不斷迴圈下去,這就是它的規律了。
因此用遞迴的方式來表示這個過程如下:
public
static
class
treenode
}public
static treenode reconstructbinarytree
(int
pre,
int[
] in)
// 利用hashmap來查詢根節點在中序遍歷中的下標,以此確定下一顆子樹的範圍
hashmap
map =
newhashmap
<
>()
;for
(int i =
0; i < in.length; i++
)return
search
(pre,
0, pre.length -
1, in,
0, in.length -
1, map);}
// (l_pre,r_pre)表示該子樹在前序遍歷中的下標範圍,(l_in,r_in)表示該子樹在中序遍歷中的下標範圍
public
static treenode search
(int
pre,
int l_pre,
int r_pre,
int[
] in,
int l_in,
int r_in, hashmap
map)
int index = map.
get(pre[l_pre]);
treenode head =
newtreenode
(pre[l_pre]);
head.left =
search
(pre, l_pre +
1, l_pre + index - l_in, in, l_in, index -
1, map)
; head.right =
search
(pre, l_pre + index - l_in +
1, r_pre, in, index +
1, r_in, map)
;return head;
}//輸出後序遍歷
public
static
void
print
(treenode tree)
print
(tree.left)
;print
(tree.right)
; system.out.
println
(tree.val);}
public
static
void
main
(string[
] args)
;int
in =
newint
; treenode resulttree =
reconstructbinarytree
(pre, in)
;print
(resulttree)
;}
搜尋函式主要難點在於下一顆左右子樹範圍的確認,以下說明助你理解。 劍指offer(四) 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。我們先來弄懂前序遍歷和中序遍歷的特點 前序遍歷 根結點 左子樹 右子樹。中序遍歷 左子樹 根結點 右子樹。所以前序遍歷序列的第乙個值...
劍指Offer 四 重建二叉樹
解法1 前序遍歷的第乙個數為樹的根,而中序遍歷中根所在位置的左面的序列即為左子樹的中序遍歷,右面即為右子樹的中序遍歷,遞迴找到每個子樹的根就ok了!class solution 返回構造的treenode根節點 def reconstructbinarytree self,pre,tin write...
劍指Offer 四 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。coding utf 8 class treenode def init self,x self.val x self.left n...