首页 > 代码库 > Construct Binary Tree from Inorder and Postorder Traversal

Construct Binary Tree from Inorder and Postorder Traversal

原题如下;

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