首页 > 其他 > 详细

[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-12-04 18:00:50      阅读:232      评论:0      收藏:0      [点我收藏+]

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,inorder,0,preorder.length-1,0,inorder.length-1);
	}
	
	private TreeNode buildTree(int []preorder, int []inorder,int pst,int pend,int inst, int inend){
		if(pst>pend||inst>inend||preorder.length<1){
			return null;
		}
		TreeNode tn =new TreeNode(preorder[pst]);
		int index = -1;
		for(int i=inst;i<=inend;i++){
			if(inorder[i] == preorder[pst]){
				index = i;
				break;
			}
		}
		tn.left = buildTree(preorder,inorder,pst+1,pst+index-inst,inst,inst+index-1);
		tn.right = buildTree(preorder,inorder,pst+index-inst+1,pend,index+1,inend);
		return tn;
	}
}




[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

原文:http://blog.csdn.net/guorudi/article/details/41726411

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!