Leetcode 106 Construct Binary Tree from Inorder and Postorder Traversal

2018-01-12 14:55:51 浏览数 (4)

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

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

中序和后序还原二叉树。

直接在上一题的代码上做一点小修改就行了。

代码语言:javascript复制
/**
 * 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* dfs(vector<int>& preorder, int ps,int pe,vector<int>& inorder,int is,int ie)  
    {  
        if(ps>pe ) return NULL;  
        TreeNode* root=new TreeNode(preorder[pe]);  
        int pos;  
        for(int i=is;;i  )  
        if(inorder[i]==preorder[pe])  
        {  
            pos=ie-i;  
            break;  
        }  
        root->left=dfs(preorder,ps,pe-pos-1,inorder,is,ie-pos-1);  
        root->right=dfs(preorder,pe-pos,pe-1,inorder,ie-pos 1,ie);  
        return root;  
    }  
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return dfs(postorder,0,inorder.size()-1,inorder,0,inorder.size()-1);
    }
};

1 人点赞