标签:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
[Solution]
先序定根,根据先序的根,中序定左右。然后递归。
1 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 2 { 3 if (preorder.size() == 0) 4 return NULL; 5 return buildTreePI(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); 6 } 7 8 TreeNode *buildTreePI(vector<int> &preorder, int preStart, int preEnd, vector<int> &inorder, int inStart, int inEnd) 9 { 10 TreeNode *root = new TreeNode(preorder[preStart]); 11 int left = 0; 12 if (preStart == preEnd) 13 return root; 14 15 while (inorder[left + inStart] != preorder[preStart]) 16 left++; 17 18 if (left > 0) 19 root->left = buildTreePI(preorder, preStart + 1, preStart + left, inorder, inStart, inStart + left - 1); 20 if (inStart + left < inEnd) 21 root->right = buildTreePI(preorder, preStart + left + 1, preEnd, inorder, inStart + left + 1, inEnd); 22 return root; 23 }
leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4295669.html