标签:tree solution hat bsp ons lse 代码 根据 get
问题描述:
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
解题思路:
我学习了大佬的解法
用辅助函数来辅助简历,根据先序遍历的特点,数组第一个点一定是根节点,而中序遍历中,根节点放在中间。
我们可以提取出根节点后,将数组分为左子树和右子树
对于中序遍历我们可以找到与根节点值相同的点并得到它的坐标 i ,那么左子树和右子树的范围分别为:
左子树:[iL, i-1] 个数: i - iL
右子树: [i+1, iR] 个数: iR - i
我们可以推出前序遍历中左右子树的位置:
左子树:[pL+1, pL+ i - iL]
右子树:[pL + i - iL + 1, pR]
代码:
/** * 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 build(preorder, 0, preorder.size()-1, inorder, 0, inorder.size() -1 ); } private: TreeNode* build(vector<int>& preorder, int pL, int pR, vector<int>& inorder, int iL, int iR){ if(pL > pR || iL > iR){ return NULL; } int i = 0; for(i = iL; i<= iR; i++){ if(inorder[i] == preorder[pL]) break; } TreeNode* cur = new TreeNode(preorder[pL]); cur->left = build(preorder, pL+1, pL + i - iL, inorder, iL, i-1); cur->right = build(preorder, pL + i-iL+1, pR, inorder, i+1, iR); return cur; } };
该解法总耗时35ms
来看一下10ms的解法:看不懂:)
/** * 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) { int p = 0, i = 0; int end = inorder.size(); return dfs(preorder, inorder, p, i, end); } TreeNode* dfs(vector<int>& preorder, vector<int>& inorder, int& p, int& i, int end) { if(i < inorder.size() && (end == inorder.size() || inorder[i] != preorder[end])) { TreeNode* ret = new TreeNode(preorder[p++]); ret->left = dfs(preorder, inorder, p, i, p-1); ++i; ret->right = dfs(preorder, inorder, p, i, end); return ret; } else return NULL; } };
105. Construct Binary Tree from Preorder and Inorder Traversal
标签:tree solution hat bsp ons lse 代码 根据 get
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9171685.html