码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal

时间:2015-05-23 19:56:06      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Construct Binary Tree from Inorder and Postorder Traversal

Total Accepted: 31041 Total Submissions: 115870

 
 

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实现如下:

	static public TreeNode buildTree(int[] inorder, int[] postorder) {
		 return buildTree(postorder, inorder, 0, postorder.length-1, 0, inorder.length-1);  
    }  
    static public TreeNode buildTree(int[] postorder, int[] inorder, int pBegin, int pEnd, int iBegin, int iEnd){  
        if(pBegin>pEnd)  
            return null;  
        TreeNode root = new TreeNode(postorder[pEnd]);  
        int i = iBegin;  
        for(;i<iEnd;i++)
            if(inorder[i]==root.val)  
                break;  
        int lenLeft = i-iBegin;  
        root.left = buildTree(postorder, inorder, pBegin, pBegin+lenLeft-1, iBegin, i-1);  
        root.right = buildTree(postorder, inorder, pBegin+lenLeft, pEnd-1, i+1, iEnd);  
        return root;
    }

 

Java for LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4524684.html

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