LeeCode 106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:众途汽修软件 编辑:程序博客网 时间:2024/06/13 10:39

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

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

recursive answer:

class Solution {public:    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {        return myBT2(postorder.size() - 1,postorder,0,inorder.size() - 1,inorder);    }        TreeNode * myBT2(int postID,vector<int>& postorder,int inID,int inEnd,vector<int>& inorder){        if(postID < 0 || inID > inEnd) return NULL;        TreeNode * root = new TreeNode(postorder[postID]);        int i;        for(i = inID; i <= inEnd; i ++ ){            if(inorder[i] == postorder[postID])                break;        }                root->left = myBT2(postID - (inEnd - i) - 1 ,postorder,inID,i - 1,inorder);        root->right = myBT2(postID - 1,postorder,i + 1,inEnd,inorder);        return root;    }};



0 0
原创粉丝点击