标签:com otv note and src ret hat nbsp root
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / 9 20 / 15 7
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { int length = inorder.length; return buildTree(inorder, 0, length - 1, postorder, 0, length - 1); } public TreeNode buildTree(int[] inorder, int instart, int inend, int[] postorder, int postart, int postend){ if(instart > inend || postart > postend) return null; int rootval = postorder[postend]; int rootind = 0; for(int i = instart; i <= inend; i++){ if(rootval == inorder[i]){ rootind = i; break; } } int len = rootind - instart; TreeNode root = new TreeNode(rootval); root.left = buildTree(inorder, instart, rootind-1, postorder, postart, postart + len - 1); root.right = buildTree(inorder, rootind + 1, inend, postorder, postart + len, postend-1 ); return root; } }
106. Construct Binary Tree from Inorder and Postorder Traversal
标签:com otv note and src ret hat nbsp root
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11441287.html