劍指offer-Java實現:題目4、重建二叉樹
阿新 • • 發佈:2018-12-27
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
思路:瞭解二叉樹的前,中,後序遍歷的規律,我們就可以知道,通過前 中,或者 後 中 兩種都能得到二叉樹。主要通過三個步驟:
1.檢視前(後)序遍歷序列,最開始(後面)的必然是根節點。
2.獲得根節點後,檢視中序遍歷序列,根節點左右兩邊分別為左子樹的所有節點,和右子樹的所有節點 4 7 2 ,5 3 8 6.
3.分別對兩邊序列重複 1 . 2 兩個步驟。最終能得到二叉樹。
程式碼:
import java.util.Arrays; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if (pre == null || in == null) { return null; } if (pre.length == 0 || in.length == 0) { return null; } if (pre.length != in.length) { return null; } TreeNode root = new TreeNode(pre[0]); for (int i = 0; i < pre.length; i++) { if (pre[0] == in[i]) { root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1), Arrays.copyOfRange(in,0,i)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length), Arrays.copyOfRange(in,i+1,in.length)); } } return root; } }