leetcode Construct Binary Tree from Preorder and Inorder Traversal
如果你没有做过根据中序遍历和后序遍历构造树,那么请先看Construct Binary Tree from Inorder and Postorder Traversal。
这题是:根据前序遍历和中序遍历构造树。
类似上一题的思路,我们可以断定正确的是中序遍历的起始下标,和前序遍历左子树的起点下标,以及右子树结束下标。根据长度一致性,来确定未知的下标即可。不难吧。
代码: 本文地址
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *fun106(vector<int> &preorder, int ps, int pe, vector<int> &inorder, int is, int ie) { if (ps > pe || is > ie) return NULL; TreeNode *root = new TreeNode(preorder[ps]); int rootval = root -> val, rootIndex; for (int i = 0; i <= ie; ++i) { if (inorder[i] == rootval) rootIndex = i; } root -> left = fun106(preorder, ps + 1, rootIndex-1-is+ps+1,inorder, is, rootIndex - 1); root -> right = fun106(preorder, pe-(ie-(rootIndex+1)), pe, inorder, rootIndex + 1, ie); return root; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if (preorder.size() == 0) return NULL; return fun106(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } };