Leetcode:106.從中序與後序遍歷序列構造二叉樹
阿新 • • 發佈:2019-02-11
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder = [9,3,15,20,7] 後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
3 / \ 9 20 / \ 15 7
解題思路:
與Leetcode105.從中序與先序遍歷序列構造二叉樹思路類似,請檢視105題的解題思路,連結如下。
不同之處是,後續遍歷的陣列最後一個是根結點,理根結點近的是右子樹,除此之外是左子樹。
/** * 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>& inorder, vector<int>& postorder) { int size_in = inorder.size(), size_post = postorder.size(); if (size_in == 0 || size_post == 0) return NULL; in = inorder; post = postorder; for (int i = 1; i <= size_in; i++) { mp[inorder[i - 1]] = i - 1; } TreeNode* root = build(0, size_in, 0, size_post); return root; } TreeNode* build(int in_first, int in_last, int post_first, int post_last) { if (in_first == in_last || post_first == post_last) return NULL; if (in_first + 1 == in_last || post_first + 1 == post_last) return new TreeNode(post[post_first]); int pos = mp[post[post_last - 1]]; TreeNode* root = new TreeNode(post[post_last - 1]); root->left = build(in_first, pos, post_first, post_last - 1 - (in_last - pos - 1)); root->right = build(pos + 1, in_last, post_last - 1 - (in_last - pos - 1), post_last - 1); return root; } private: vector<int> in, post; unordered_map<int, int> mp; }; |