首页 > 其他 > 详细

LeetCode Construct Binary Tree from Preorder and Inorder Traversal

时间:2015-05-02 11:14:16      阅读:169      评论: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 a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode build(int[] preorder, int[] inorder, int l, int r, int len) {
		TreeNode root = null;
		if (len < 1) return root;
		root = new TreeNode(preorder[l]);
		
		int index = 0;
		for (int i = 0; i < len; i++) 
			if (inorder[r+i] == preorder[l]) {
				index = i;
				break;
			}
		
		root.left = build(preorder, inorder, l+1, r, index);
		root.right = build(preorder, inorder, l+1+index, r+1+index, len-1-index);
		return root;
	}
	
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    	int n = preorder.length;
    	return build(preorder, inorder, 0, 0, n);
    }
}



LeetCode Construct Binary Tree from Preorder and Inorder Traversal

原文:http://blog.csdn.net/u011345136/article/details/45437741

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