/**
* definition for binary tree
* public class treenode
* }*/public
class
solution
int val = pre[prel]
;// 前序遍歷序列中的第乙個數即為根節點
treenode tree =
newtreenode
(val)
;int mid =0;
// 找到根節點在中序遍歷中的位置
for(
int i = inl; i <= inr; i++)}
// 在中序遍歷中,根節點把序列分為左右子樹
int leftcount = mid - inl;
// 左子樹節點個數
int rightcount = inr - mid;
// 右子樹節點個數
// 分別遞迴構造左右子樹
tree.left =
dfs(pre, in, prel +
1, prel + leftcount, inl, mid -1)
; tree.right =
dfs(pre, in, prer - rightcount +
1, prer, mid +
1, inr)
;return tree;
}public treenode reconstructbinarytree
(int
pre,
int[
] in)
return
dfs(pre, in,
0, lenpre -1,
0, lenin -1)
;}}
劍指offer程式設計題《重建二叉樹》
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。我們都知道,通過前序遍歷和中序遍歷或後序遍歷和中序遍歷可以唯一確定一棵二叉樹。前序 根 左 右 中序 左 根 右 後序 左 右 根 ...
劍指offer程式設計題 重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。這道題目是一道非常經典的題目,這裡可以用乙個hash表存下中序遍歷的value的index,可以快速找到index definiti...
劍指offer程式設計題 重建二叉樹
題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。方案 在二叉樹的前序遍歷序列中,第乙個數字總是樹的根節點的值 在二叉樹的中序遍歷序列中,根節點的值在序列的中間,根節點左側...