Construct Binary Tree from Preorder and Inorder Traversal
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Construct Binary Tree from Preorder and Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
606. Construct String from Binary Tree
606. Construct String from Binary Tree
LeetCode Construct String from Binary Tree
Construct String From Binary Tree