LeetCode OJ 106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode OJ 106. Construct Binary Tree from Inorder and Postorder Traversal


Description

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

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

解題思路

這道題跟題目105相似,只是前序遍歷變成了後序遍歷。根據二叉樹的中序遍歷和後序遍歷構造二叉樹。因爲題目中提示了節點沒有重複的值,所以我們可以判斷節點的值來找出根節點。後序遍歷的最後一個節點是當前子樹的根節點,由此,我們可以找到根節點在中序便利中的位置root_i,把中序遍歷分爲兩部分:這個根節點的左右子樹的中序遍歷。同時,後序遍歷可以根據這個查找的偏移量root_i把前序遍歷分爲兩部分:這個根節點的左右子樹的後序遍歷。這樣就可以遞歸構造這個根節點的左右子樹了。

Note:

vetctor容器中的assign()函數:
函數原型:

void assign(const_iterator first,const_iterator last);

void assign(size_type n,const T& x = T());

功能:

將區間[first,last)的元素賦值到當前的vector容器中,或者賦n個值爲x的元素到vector容器中。注意是不含last這個元素的!這是cplusplus.com的說明鏈接

代碼

個人github代碼鏈接

/**
 * 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) {
        TreeNode* root;
        if(postorder.size() == 0 || inorder.size() == 0)
            return NULL;
        if(postorder.size() == 1)
        {
            root = new TreeNode(postorder[0]);
            return root;
        }
        root = new TreeNode(postorder[postorder.size()-1]);
        int root_i = 0;
        vector<int>::iterator root_itr = inorder.begin();
        for(root_itr; root_itr != inorder.end(); root_itr++){
            if(root->val == (*root_itr)){
                break;
            }
            root_i ++;
        }
        vector<int> left_post,right_post,left_in,right_in;
        vector<int>::iterator itr = postorder.begin();
        left_post.assign(itr, itr + root_i);
        right_post.assign(itr + root_i, postorder.end() - 1);
        itr = inorder.begin();
        left_in.assign(itr,root_itr);
        right_in.assign(root_itr + 1, inorder.end());
        root->left = buildTree(left_in, left_post);
        root->right = buildTree(right_in, right_post);
        return root;
    }
};

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