LeetCode | Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:数据分析职业发展 编辑:程序博客网 时间:2024/06/05 08:57

题目:

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

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


思路:

postorder的最后一位始终是子树的根结点。根据该根结点查找inorder中的序列可以判断该子树是否存在左子树与右子树。若存在,递归建立子树。

代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int cur;    vector<int> postorder;    vector<int> inorder;    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {        if(postorder.size() == 0)            return NULL;        else        {            this->postorder = postorder;            this->inorder = inorder;            cur = postorder.size()-1;                        return buildSubTree(0, inorder.size()-1);                    }    }        TreeNode * buildSubTree(int from, int to)    {        TreeNode* root = new TreeNode(postorder[cur]);        int index = findValInInOrder(postorder[cur]);        cur--;        if(index >= to)        {            root->right = NULL;        }        else        {            root->right = buildSubTree(index+1,to);        }        if(index <= from)        {            root->left = NULL;        }        else        {            root->left = buildSubTree(from, index-1);        }        return root;    }        int findValInInOrder(int val)    {        for(int i=0;i<inorder.size();i++)        {            if(inorder[i] == val)            {                return i;            }        }        return -1;        }    };


0 0
原创粉丝点击