您的位置:首页 > 编程语言 > Java开发

[leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal@Java结题报告

2017-08-07 10:03 549 查看
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

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

Note:

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

package go.jacob.day807;

/**
* 106. Construct Binary Tree from Inorder and Postorder Traversal
*
* @author Jacob
*
*/
public class Demo1 {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null)
return null;

return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}

private TreeNode buildTree(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight) {
if (inLeft > inRight)
return null;
TreeNode root = new TreeNode(postorder[postRight]);
// 只有一个节点,返回root
if (inLeft == inRight)
return root;
int rootNum = 0;
for (int i = inLeft; i <= inRight; i++) {
if (inorder[i] == postorder[postRight]) {
rootNum = i;
break;
}
}

int leftLength = rootNum - inLeft;
//递归左子树和右子树
root.left = buildTree(inorder, inLeft, inLeft + leftLength - 1, postorder, postLeft, postLeft + leftLength - 1);
root.right = buildTree(inorder, inLeft + leftLength + 1, inRight, postorder, postLeft + leftLength,
postRight - 1);

return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐