2018.7.8學習筆記
阿新 • • 發佈:2019-01-03
劍指Offer P62 面試題7:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if (pre == null || in == null || pre.length == 0 || in.length == 0) return null; TreeNode root = new TreeNode(pre[0]); for (int location = 0; location < in.length; location++) { if (pre[0] == in[location]) { // 左子樹 int[] leftPre = new int[location]; int[] leftIn = new int[location]; for (int i = 0; i < location; i++) { leftPre[i] = pre[i + 1]; leftIn[i] = in[i]; } root.left = reConstructBinaryTree(leftPre, leftIn); // 右子樹 int[] rightPre = new int[in.length - 1 - location]; int[] rightIn = new int[in.length - 1 - location]; for (int i = 0; i < in.length - 1 - location; i++) { rightPre[i] = pre[location + 1 + i]; rightIn[i] = in[location + 1 + i]; } root.right = reConstructBinaryTree(rightPre, rightIn); } } return root; } }
遞迴呼叫的時候一定要寫
root.left =
root.right =
如果允許匯入相關包的話,就不用建立新陣列了
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, location+1), Arrays.copyOfRange(in, 0, location)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, location+1, pre.length), Arrays.copyOfRange(in, location+1, in.length));