您的位置:首页 > 其它

LeetCode | Construct Binary Tree from Inorder and Postorder Traversal

2013-12-17 20:26 351 查看


题目:

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;    
    }
    
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐