Given inorder and postorder traversal of a tree, construct the binary tree.
Given inorder [1,2,3]
and postorder [1,3,2]
, return a tree:
2
/ 1 3
/** * 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; } }
时间: 2024-10-12 09:12:57