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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-01-07 01:52:25      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:inorder postorder tr

原题如下;

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

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

题意很简单:根据中序遍历和后序遍历的序列生成树


思路很简单:根据后序遍历的序列确定根节点,在中序遍历中找到根节点,将原来的序列分为左右两个部分,递归解决左右两个部分就可以解决这个问题。

Java代码如下:


public class ConstructBinaryTreefromInorderandPostorderTraversal {

	/**
	 * @Construct Binary Tree from Inorder and Postorder Traversal 
	 * link:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
	 * idea:递归
	 */
	
	class TreeNode{
		int val;
		TreeNode left;
		TreeNode right;
		public TreeNode(int x) {
			val=x;
		}
	}
	
	
	
	
	class Solution {
	    public TreeNode buildTree(int[] inorder, int[] postorder) {
	        if(inorder.length==0){
	        	return null;
	        }
	        
	        TreeNode node=createTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
	        return node;
	    }
	    
	    public TreeNode createTree(int[] inorder,int inbegin,int inend,int[] postorder,int postbegin,int postend){
	    	if(inbegin>inend){
	    		return null;
	    	}
	    	
	    	int  root=postorder[postend];
	    	int index=0;
	    	for(int i=inbegin;i<=inend;i++){
	    		if(root==inorder[i]){
	    			index=i;
	    			break;
	    		}
	    	}
	    	
	    	int len=index-inbegin;
	    	TreeNode left=createTree(inorder, inbegin, index-1, postorder, postbegin, postbegin+len-1);
	    	TreeNode right=createTree(inorder, index+1, inend, postorder, postbegin+len, postend-1);
	    	TreeNode node=new TreeNode(root);
	    	node.left=left;
	    	node.right=right;
	    	return node;
	    }
	}

}


Construct Binary Tree from Inorder and Postorder Traversal

标签:inorder postorder tr

原文地址:http://blog.csdn.net/ivyvae/article/details/42478913

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