您的位置:首页 > 其它

[LintCode] 前序遍历和中序遍历树构造二叉树 Construct Binary Tree from Preorder and Inorder Traversal

2016-04-17 22:27 501 查看
根据前序遍历和中序遍历树构造二叉树.

注意事项

你可以假设树中不存在相同数值的节点.

样例

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

2

/ \

1 3

Given preorder and inorder traversal of a tree, construct the binary tree.

Notice

You may assume that duplicates do not exist in the tree.

Example

Given in-order [1,2,3] and pre-order [2,1,3], return a tree:

2

/ \

1 3

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/

public class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(null == preorder || null == inorder || preorder.length != inorder.length || preorder.length == 0) return null;
return createTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
}

public TreeNode createTree(int[] preorder, int lp, int rp, int[] inorder, int li, int ri) {
if(lp > rp || li > ri) return null;
TreeNode root = new TreeNode(preorder[lp]);
int inlo = location(inorder, preorder[lp]);
root.left = createTree(preorder, lp+1, lp+inlo-li,inorder, li, inlo-1);
root.right = createTree(preorder, lp+inlo-li+1, rp,inorder, inlo+1, ri);
return root;
}

public int location(int[] nums, int key) {
int i = 0;
while(nums[i++] != key);
return --i;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: