您的位置:首页 > 其它

LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

2014-07-03 19:10 531 查看
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

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

思路:递归

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		return buildTree(preorder, 0,preorder.length-1,inorder,0,inorder.length-1);
	}
	public TreeNode buildTree(int[] preorder, int s1,int e1,int[] inorder,int s2,int e2) {
		if(s1<=e1&&s2<=e2){
			TreeNode temp=new TreeNode(preorder[s1]);
			int i=s2;
			for(;i<=e2&&inorder[i]!=preorder[s1];i++);
			temp.left=buildTree(preorder,s1+1,s1+i-s2,inorder,s2,i-1);
			temp.right=buildTree(preorder,s1+i-s2+1,e1,inorder,i+1,e2);
			return temp;
		}else return null;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐