《劍指offer》之重構二叉樹
題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
分析:兩種遍歷的區別爲:
前序遍歷:根結點 —> 左子樹 —> 右子樹
中序遍歷:左子樹—> 根結點 —> 右子樹
解決方案:
-
我們可以根據前序遍歷得到根節點,然後再在中序遍歷中找到該節點的左子樹和右子樹。然後利用遞歸的思想,將左子樹和右子樹又分別進行重構,從而實現整個二叉樹的重構。
代碼:
public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); } private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) { if(startPre>endPre||startIn>endIn){ return null; } TreeNode root=new TreeNode(pre[startPre]); for(int i=startIn;i<=endIn;i++){ if(in[i]==pre[startPre]){ root.left=reConstructBinaryTree(pre,startPre+1,startPre+(i-startIn),in,startIn,i-1); root.right=reConstructBinaryTree(pre,startPre+(i-startIn)+1,endPre,in,i+1,endIn); break; } } return root; }
-
測試性能分析
運行時間:262ms
佔用內存:22756k