Created
August 12, 2017 19:59
-
-
Save cixuuz/81d7ebee8833b156dde1753bcb5b23b3 to your computer and use it in GitHub Desktop.
[105. Construct Binary Tree from Preorder and Inorder Traversal] #lc_105
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public TreeNode buildTree(int[] preorder, int[] inorder) { | |
return dfs(preorder, inorder, 0, 0, preorder.length); | |
} | |
private TreeNode dfs(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd) { | |
if (inStart > inEnd || preStart >= preorder.length) return null; | |
TreeNode node = new TreeNode(preorder[preStart]); | |
Integer idx = 0; | |
while (inorder[idx] != preorder[preStart]) { | |
idx++; | |
} | |
node.left = dfs(preorder, inorder, preStart+1, inStart, idx-1); | |
node.right = dfs(preorder, inorder, preStart+idx-inStart+1, idx+1, inEnd); | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment