106. Construct Binary Tree from Inorder and Postorder Traversal
Posted warmland
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了106. Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。
和105是一样的
1 public TreeNode buildTree(int[] inorder, int[] postorder) { 2 if(inorder.length == 0 || postorder.length != inorder.length) { 3 return null; 4 } 5 int len = inorder.length; 6 return helper(inorder, postorder, 0, len - 1, 0, len - 1); 7 } 8 9 private TreeNode helper(int[] inorder, int[] postorder, int inStart, int inEnd, int postStart, int postEnd) { 10 if(inStart > inEnd || postStart > postEnd) { 11 return null; 12 } 13 TreeNode root = new TreeNode(postorder[postEnd]); 14 int rootIndex = indexOf(inorder, postorder[postEnd]); 15 int leftLen = rootIndex - inStart; 16 int rightLen = inEnd - rootIndex; 17 root.left = helper(inorder, postorder, inStart, rootIndex - 1, postStart, postStart + leftLen - 1); 18 root.right = helper(inorder, postorder, rootIndex + 1, inEnd, postEnd - rightLen, postEnd - 1); 19 return root; 20 } 21 22 private int indexOf(int[] arr, int key) { 23 for(int i = 0; i < arr.length; i++) { 24 if(arr[i] == key) { 25 return i; 26 } 27 } 28 return -1; 29 }
以上是关于106. Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal