标签:
题目描述:/** * 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) { TreeNode node = null; var len = postorder.Length - 1; Build(ref node, inorder, 0, len, postorder, 0, len); return node; } private void Build(ref TreeNode current, int [] inorder, int iFrom, int iTo, int[] postorder, int pFrom, int pTo) { if(iFrom > iTo || pFrom > pTo){ return; } // set current current = new TreeNode(postorder[pTo]); // take the last one from post order , because it is the root var pLast = postorder[pTo]; // find its index in inorder var index = -1; for(var i = iFrom;i <= iTo; i++){ if(inorder[i] == pLast){ index = i; break; } } // for left sub tree , inorder : [0, index) . postorder : [pFrom, pFrom + distance(index, iFrom) - 1) Build(ref current.left, inorder, iFrom, index - 1, postorder, pFrom, pFrom + index - iFrom - 1); // for right sub tree , inorder : [index + 1, len), postorder : [pFrom + distance(index, iFrom), pTo-1] Build(ref current.right, inorder, index + 1, iTo ,postorder, pFrom + index - iFrom, pTo - 1); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode -- Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48896981