[LeetCode][105,106] Construct Binary Tree from Inorder and (Post/Pre)order Traversal

Description:

Given (pre/post)order and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

——————————————————————————————————————————————————————————————————————————

Solution:

題意:通過前序遍歷和中序遍歷,或後序遍歷和中序遍歷,構造一棵二叉樹。

思路:遞歸構造。


由前序遍歷和中序遍歷:

/**
 * 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) {
        this->preorder = preorder;
        this->inorder = inorder;
        return constructTree(0, 0, inorder.size() - 1);
    }
    TreeNode* constructTree(int preStart, int inStart, int inEnd) {
        if (preStart >= preorder.size() || inStart > inEnd)
            return NULL;
        int curIndex = 0;
        TreeNode* curRoot = new TreeNode(preorder[preStart]);
        for (int i = inStart; i <= inEnd; i++) {
            if (preorder[preStart] == inorder[i]) {
                curIndex = i;
                break;
            }
        }
        curRoot->left = constructTree(preStart + 1, inStart, curIndex - 1);
        curRoot->right = constructTree(preStart + curIndex - inStart + 1, curIndex + 1, inEnd);
        return curRoot;
    }
private:
    vector<int> preorder, inorder;
};

由後序遍歷和中序遍歷:

/**
 * 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) {
        this->postorder = postorder;
        this->inorder = inorder;
        return constructTree(postorder.size() - 1, 0, inorder.size() - 1);
    }
    TreeNode* constructTree(int postStart, int inStart, int inEnd) {
        if (postStart < 0 || inStart > inEnd)
            return NULL;
        int curIndex = 0;
        TreeNode* curRoot = new TreeNode(postorder[postStart]);
        for (curIndex = inStart; curIndex <= inEnd; curIndex++) 
            if (postorder[postStart] == inorder[curIndex]) 
                break;
        
        curRoot->left = constructTree(postStart - (inEnd - curIndex) - 1, inStart, curIndex - 1);
        curRoot->right = constructTree(postStart - 1, curIndex + 1, inEnd);
        return curRoot;
    }
private:
    vector<int> postorder, inorder;
};


發佈了81 篇原創文章 · 獲贊 60 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章