码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-11-23 10:32:58      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:算法   leetcode   

问题描述:

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 {   //java
    public TreeNode buildSubTree(int [] preorder, int pbegin, int pend, int [] inorder, int ibegin, int iend){
		TreeNode root = null;
		if(pbegin > pend || ibegin > iend)
			return root;
		if(pbegin == pend){
			TreeNode tmp = new TreeNode(preorder[pbegin]);
			root = tmp;
			return root;
		}
		
		int value = preorder[pbegin];
		int pos = 0;
		
		for(int i = ibegin; i <=iend; i++){
			if(value == inorder[i]){
				pos = i;
				break;
			}
		}
		
		int lnum = pos - ibegin;
		int rnum = iend - pos;
		TreeNode ltreeNode = buildSubTree(preorder,pbegin+1,pbegin+lnum,inorder,ibegin,pos-1);
		TreeNode rTreeNode = buildSubTree(preorder, pbegin+lnum+1, pend, inorder, pos+1, iend);
		TreeNode tmp = new TreeNode(preorder[pbegin]);
		tmp.left = ltreeNode;
		tmp.right = rTreeNode;
		root = tmp;
		return root;
	}
	public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode root = null;
		if(preorder.length == 0)
        	return root;
		 root = buildSubTree(preorder , 0 , preorder.length-1, inorder, 0, inorder.length-1);
		 return root;
    }
}


[leetcode]Construct Binary Tree from Preorder and Inorder Traversal

标签:算法   leetcode   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41408319

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!