标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Tree Array Depth-first Search
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 == null || postorder == null) { 13 return null; 14 } 15 16 return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1); 17 } 18 19 public TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) { 20 if (inL > inR) { 21 return null; 22 } 23 24 // create the root node. 25 TreeNode root = new TreeNode(postorder[postR]); 26 27 // find the position of the root node in the inorder traversal. 28 int pos = 0; 29 for (; pos <= inR; pos++) { 30 if (inorder[pos] == postorder[postR]) { 31 break; 32 } 33 } 34 35 int leftNum = pos - inL; 36 37 root.left = dfs(inorder, postorder, inL, pos - 1, postL, postL + leftNum - 1); 38 root.right = dfs(inorder, postorder, pos + 1, inR, postL + leftNum, postR - 1); 39 40 return root; 41 } 42 }
代码: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree2.java
LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
标签:
原文地址:http://www.cnblogs.com/yuzhangcmu/p/4199660.html