首页 > 代码库 > Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
与Construct Binary Tree from Inorder and Preorder Traversal问题非常类似,唯一区别在于这一次确定root的位置由post traversal来确定,为最后一个元素。
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public TreeNode buildTree(int[] inorder, int[] postorder) {12 if (inorder.length==0 || postorder.length==0 || inorder.length!=postorder.length) {13 return null;14 }15 int len = inorder.length;16 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();17 for (int i=0; i<inorder.length; i++) {18 map.put(inorder[i], i);19 }20 return helper(postorder, 0, len-1, inorder, 0, len-1, map);21 }22 23 public TreeNode helper(int[] postorder, int posL, int posR, int[] inorder, int inL, int inR, HashMap<Integer, Integer> map) {24 if (posL>posR || inL>inR) {25 return null;26 }27 TreeNode root = new TreeNode(postorder[posR]);28 int index = map.get(postorder[posR]);29 root.left = helper(postorder, posL, posL+index-1-inL, inorder, inL, index-1, map);30 root.right = helper(postorder, posL+index-inL, posR-1, inorder, index+1, inR, map);31 return root;32 }33 }
Leetcode: Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。