【leetcode】105. 從前序與中序遍歷序列構造二叉樹( Construct Binary Tree from Preorder and Inorder Traversal )


題目描述

【leetcode】105. 從前序與中序遍歷序列構造二叉樹( Construct Binary Tree from Preorder and Inorder Traversal )

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。

注意:
你可以假設樹中沒有重複的元素。

例如,給出

前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]

返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

第一次解答

思路
根據前序遍歷,我們可以構造二叉樹,但是結果不唯一。因爲每一次迭代,僅根據前序遍歷的約束,下一個結點所在位置有三種可能:

  1. 下個結點爲當前結點的左孩子
  2. 下個結點爲當前結點的右孩子
  3. 下個結點爲當前結點的父母或祖先的右孩子

此時我們再根據中序遍歷特點,纔可進一步確定是哪種可能。
其中前兩步的判斷都可在同一層遞歸中判斷,比較直觀;但是第三種情況,需要依次查詢當前結點的父母,父母的父母,父母的父母的父母… 直到找到合適的父母爲止,爲了實現這個過程,我們可以把中序遍歷根據父母結點分成左右子樹區間,根據區間判斷是否找到合適的父母。

代碼:

/**
 * 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:
    int index = 0;
    void PreOrder(vector<int>& preorder, vector<int>& inorder, TreeNode *&root, 
    		unordered_map<int, int> &pos, int left, int right){
    	// 根據left和right,可以知道當前元素是否是上個結點的左右子樹
    	// 若left > right,則當前元素不是上個結點的左右子樹,
    	// 應當返回,由結點的父母或祖先進行處理
        if(index >= preorder.size() || left > right)
            return;
        root = new TreeNode(preorder[index]);
        int curr_pos = pos[preorder[index]];
        index++;
        PreOrder(preorder, inorder, root->left, pos, left, curr_pos-1);
        PreOrder(preorder, inorder, root->right, pos, curr_pos+1, right);
        
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        unordered_map<int, int> pos;
        for(int i=0; i<inorder.size(); ++i){
            pos[inorder[i]] = i;
        }
        TreeNode *root = nullptr;

        PreOrder(preorder, inorder, root, pos, 0, inorder.size()-1);

        return root;
    }
};

結果:

截圖

相關/參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章