106. Construct Binary Tree from Inorder and Postorder Traversal
Posted gopanama
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了106. Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。
1 class Solution { 2 public TreeNode buildTree(int[] inorder, int[] postorder) { 3 return helper(postorder.length-1, 0, inorder.length - 1, inorder, postorder); 4 5 } 6 7 public TreeNode helper(int post, int inStart, int inEnd, int[] inorder, int[] postorder) { 8 if(inStart > inEnd || post < 0) { 9 return null; 10 } 11 TreeNode root = new TreeNode(postorder[post]); 12 int rootIndex = 0; 13 for(int i = inStart; i <= inEnd; i++) { 14 if(inorder[i] == root.val) { 15 rootIndex = i; 16 break; 17 } 18 } 19 20 root.right = helper(post-1, rootIndex+1, inEnd, inorder, postorder); 21 root.left = helper(post - (inEnd - rootIndex + 1), inStart, rootIndex - 1, inorder, postorder ); 22 // inEnd - rootIndex注意是inEnd去减, 不是inorder.length 23 return root; 24 } 25 }
以上是关于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