您的位置:首页 > 其它

LeetCode OJ Construct Binary Tree from Inorder and Postorder Traversal

2015-03-22 18:30 267 查看
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

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

给中序遍历和后序遍历,构造二叉树。

class Solution {
public:
    TreeNode * buildTree( vector<int> &inorder, vector<int> &postorder) {
        if (postorder.size() == 0) return NULL;
        post = postorder;
        in = inorder;
        TreeNode * newRoot;
        makeBTreeByPreIn(&newRoot, post.size() - 1, 0, post.size() - 1);
        return newRoot;
    }
    void makeBTreeByPreIn(TreeNode ** nowRoot, int posInPost, int searchS, int searchE) {
        *nowRoot = new TreeNode(post[posInPost]);
        int leftTreeLength, rightTreeLength, leftS, leftE, rightS, rightE;
        leftS = searchS;
        rightE = searchE;
        for (int i = searchS; i <= searchE; i++) {  // find the nowRoot's data in searching range of the inorder vector
            if (in[i] == post[posInPost]) {
                leftE = i - 1;
                rightS = i + 1;
                break;
            }
        }
        leftTreeLength = leftE - leftS  + 1;
        rightTreeLength = rightE - rightS + 1;
        if (leftTreeLength != 0) makeBTreeByPreIn(&((*nowRoot)->left), posInPost - rightTreeLength - 1, leftS, leftE);
        if (rightTreeLength != 0) makeBTreeByPreIn(&((*nowRoot)->right), posInPost - 1, rightS, rightE);
    }
private:
    vector<int> post;
    vector<int> in;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: