面试题07-II 根据前序和后序遍历构造二叉树
时间:2022-05-10 13:05
题目:
解答:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public TreeNode constructFromPrePost(int[] pre, int[] post) 12 { 13 int N = pre.length; 14 if (N == 0) 15 { 16 return null; 17 } 18 TreeNode root = new TreeNode(pre[0]); 19 if (N == 1) 20 { 21 return root; 22 } 23 24 int L = 0; 25 for (int i = 0; i < N; ++i) 26 if (post[i] == pre[1]) 27 L = i+1; 28 29 root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L+1), 30 Arrays.copyOfRange(post, 0, L)); 31 root.right = constructFromPrePost(Arrays.copyOfRange(pre, L+1, N), 32 Arrays.copyOfRange(post, L, N-1)); 33 return root; 34 35 } 36 }