0
点赞
收藏
分享

微信扫一扫

【Leetcode】Construct Binary Tree from Inorder and Postorder Traversal

王远洋 2023-07-26 阅读 16


题目链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题目:

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

思路:

easy

算法:

 

1. public TreeNode buildTree(int[] inorder, int[] postorder) {  
2. if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {  
3. return null;  
4.     }  
5.   
6. // 在前序排列中,从头开始查找定位: 第一个既在后序也在中序的元素位置,以及它在后序中的位置  
7. int start = -1, pindex = -1;// start是后序中的位置 index是中序的位置  
8. for (int i = postorder.length - 1; i >= 0; i--) {  
9. int tmp = search(inorder, postorder[i]);  
10. if (tmp >= 0) {  
11.             pindex = tmp;  
12.             start = i;  
13. break;  
14.         }  
15. // ====end  
16. new TreeNode(postorder[start]);  
17. if (inorder.length == 1) {  
18. return root;  
19.     }  
20. // 根据index划分中序排列  
21. int leftInorder[] = Arrays.copyOfRange(inorder, 0, pindex);  
22. int rightInorder[] = Arrays.copyOfRange(inorder, pindex + 1, inorder.length);  
23.   
24. int newpreorder[] = Arrays.copyOfRange(postorder, 0, start);  
25.   
26.     root.left = buildTree(leftInorder, newpreorder);  
27.     root.right = buildTree(rightInorder, newpreorder);  
28. return root;  
29. }  
30.   
31. public int search(int nums[], int target) {  
32. for (int i = 0; i < nums.length; i++) {  
33. if (nums[i] == target)  
34. return i;  
35.     }  
36. return -1;  
37. }

举报

相关推荐

0 条评论