lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal相关的知识,希望对你有一定的参考价值。
Given inorder and postorder traversal of a tree, construct the binary tree.
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** *@param inorder : A list of integers that inorder traversal of a tree *@param postorder : A list of integers that postorder traversal of a tree *@return : Root of a tree */ public TreeNode buildTree(int[] inorder, int[] postorder) { // write your code here if(inorder == null || inorder.length == 0) return null; int size = inorder.length; TreeNode root = build(inorder, 0, size - 1, postorder, 0, size - 1); return root; } public TreeNode build(int[] inorder, int in_start, int in_end, int[] postorder, int post_start, int post_end){ if(in_start > in_end || post_start > post_end) return null; TreeNode root = new TreeNode(postorder[post_end]); int k = in_start; for(; k < in_end; k++){ if(inorder[k] == postorder[post_end]) break; } TreeNode left = build(inorder, in_start, k - 1, postorder, post_start, post_start + k - 1 - in_start); TreeNode right = build(inorder, k + 1, in_end, postorder, post_start + k - in_start, post_end - 1); root.left = left; root.right = right; return root; } }
以上是关于lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章