1. 程式人生 > >劍指offer 6. 重建二叉樹

劍指offer 6. 重建二叉樹

輸入一棵二叉樹前序遍歷和中序遍歷的結果,請重建該二叉樹。

注意:

  • 二叉樹中每個節點的值都互不相同;
  • 輸入的前序遍歷和中序遍歷一定合法;

樣例

給定:
前序遍歷是:[3, 9, 20, 15, 7]
中序遍歷是:[9, 3, 15, 20, 7]

返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉樹如下所示:
    3
   / \
  9  20
    /  \
   15   7

從前序遍歷中可以判斷當前區間的根結點(第一個元素)
通過中序遍歷判斷每一個根節點的左右子樹(根左邊的數全部為左子樹,右邊的數全部為右子樹),可以得到左(右)子樹元素個數k
再通過前序遍歷遞迴訪問根結點的左右子樹,其中,前序遍歷的第一個元素是根結點,第2到第k+1個元素是新的左子樹

快速地找到某個數在中序遍歷的位置可以用雜湊表

/**
 * 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:
    unordered_map<int,int> pos;

    TreeNode* buildTree
(vector<int>& preorder, vector<int>& inorder) { int n = preorder.size(); for (int i = 0; i < n; i ++ ) pos[inorder[i]] = i; return dfs(preorder, inorder, 0, n - 1, 0, n - 1); } // 返回以pre[pl]為根的樹 TreeNode* dfs(vector<int>&pre,
vector<int>&in, int pl, int pr, int il, int ir) { if (pl > pr) return NULL; int k = pos[pre[pl]] - il; // k是左子樹元素個數 TreeNode* root = new TreeNode(pre[pl]); root->left = dfs(pre, in, pl + 1, pl + k, il, il + k - 1); root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir); return root; } };