/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode BuildTree(int[] inorder, int[] postorder) {
return helper(inorder, 0, inorder.Length - 1, postorder, 0, postorder.Length - 1);
}
TreeNode helper(int[] inorder, int istart, int iend, int[] postorder, int pstart, int pend)
{
for (int i = istart; i <= iend; i++)
{
// Find the root from inorder array
if (inorder[i] == postorder[pend])
{
TreeNode root = new TreeNode(inorder[i]);
root.left = helper(inorder, istart, i - 1, postorder, pstart, pstart + i - 1 - istart);
root.right = helper(inorder, i + 1, iend, postorder, pend-1 - (iend-i-1), pend - 1);
return root;
}
}
return null;
}
}
Sunday, August 21, 2016
Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
Answer:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment