劍指offer系列(4):重建二叉樹
阿新 • • 發佈:2018-12-11
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。
樣例分析
例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回{1,2,5,3,4,6,7}
思路分析
前序遍歷序列中,根節點總在最前。而中序遍歷序列中,根節點分割了左右子樹,所以,找到中序遍歷中的根節點,就知道了左右子樹,依次思路進行遞迴,即可得出答案。
程式碼及結果
public TreeNode reConstructBinaryTree(int [] pre,int [] in) { TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1); return root; } public TreeNode reConstructBinaryTree(int [] pre,int startpre,int endpre,int [] in,int startin,int endin) { if (startpre>endpre || startin>endin) { return null; } TreeNode node = new TreeNode(pre[startpre]); for (int i = startin; i <= endin; i++) { if (in[i] == pre[startpre]) { node.left = reConstructBinaryTree(pre, startpre+1, startpre+i-startin, in, startin, i-1);//不理解這裡的,可藉助長度理解,兩陣列中,左子樹部分長度相同 node.right = reConstructBinaryTree(pre, startpre+i-startin+1, endpre, in, i+1, endin); } } return node; }