Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
Approach #1: C++.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return solve(preorder, 0, inorder, 0, inorder.size()-1); } private: TreeNode* solve(vector<int>& preorder, int ps, vector<int>& inorder, int is, int ie) { if (ps > preorder.size() || is > ie) return NULL; TreeNode* root = new TreeNode(preorder[ps]); int inIndex = 0; for (int i = is; i <= ie; ++i) if (inorder[i] == root->val) inIndex = i; TreeNode* leftchild = solve(preorder, ps+1, inorder, is, inIndex-1); TreeNode* rightchild = solve(preorder, ps+inIndex-is+1, inorder, inIndex+1, ie); root->left = leftchild; root->right = rightchild; return root; } };
Approach #2: Java.
/** * 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[] preorder, int[] inorder) { return helper(0, 0, inorder.length - 1, preorder, inorder); } private TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) { if (preStart > preorder.length - 1 || inStart > inEnd) return null; TreeNode root = new TreeNode(preorder[preStart]); int inIndex = 0; for (int i = inStart; i <= inEnd; ++i) { if (inorder[i] == root.val) inIndex = i; } root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder); root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder); return root; } }
Approach #3: Python.
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if inorder: ind = inorder.index(preorder.pop(0)) root = TreeNode(inorder[ind]) root.left = self.buildTree(preorder, inorder[0:ind]) root.right = self.buildTree(preorder, inorder[ind+1:]) return root
永远渴望,大智若愚(stay hungry, stay foolish)