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

[leetcode]

时间:2014-11-23 11:51:28      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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

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


基本思路:

与前一篇《Construct Binary Tree from Preorder and Inorder Traversal 》类似,找出规律进行递归求解。


代码:

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

标签:leetcode   算法   

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

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