LeetCode: Construct Binary Tree from Preorder and Inorder Traversa
跟inorder and postorder基本一样,一次过吧
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *dfs(vector<int> &preorder, vector<int> &inorder, int prebeg, int inbeg, int len) { 13 if (!len) return NULL; 14 TreeNode *tmp = new TreeNode(preorder[prebeg]); 15 int leftlen, rightlen; 16 for (int i = inbeg; i < inbeg+len; i++) { 17 if (tmp->val == inorder[i]) { 18 leftlen = i - inbeg; 19 rightlen = len - leftlen - 1; 20 break; 21 } 22 } 23 tmp->left = dfs(preorder, inorder, prebeg+1, inbeg, leftlen); 24 tmp->right = dfs(preorder, inorder, prebeg+leftlen+1, inbeg+leftlen+1, rightlen); 25 return tmp; 26 } 27 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 28 // Start typing your C/C++ solution below 29 // DO NOT write int main() function 30 if (preorder.size() != inorder.size() || preorder.size() == 0) return NULL; 31 int len = preorder.size(); 32 return dfs(preorder, inorder, 0, 0, len); 33 } 34 };
C#
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode BuildTree(int[] preorder, int[] inorder) { 12 if (preorder.Length == 0 || preorder.Length != inorder.Length) return null; 13 int len = preorder.Length; 14 return dfs(preorder, inorder, 0, 0, len); 15 } 16 TreeNode dfs(int[] preorder, int[] inorder, int prebeg, int inbeg, int len) 17 { 18 if (len == 0) return null; 19 TreeNode tmp = new TreeNode(preorder[prebeg]); 20 int leftlen = 0; 21 int rightlen = 0; 22 for (int i = inbeg; i < inbeg+len; i++) { 23 if (tmp.val == inorder[i]) { 24 leftlen = i - inbeg; 25 rightlen = len - leftlen - 1; 26 break; 27 } 28 } 29 tmp.left = dfs(preorder, inorder, prebeg+1, inbeg, leftlen); 30 tmp.right = dfs(preorder, inorder, prebeg+leftlen+1, inbeg+leftlen+1, rightlen); 31 return tmp; 32 } 33 }