lintcode 前序遍历和中序遍历构造二叉树

根据前序遍历和中序遍历树构造二叉树.
注意事项
你可以假设树中不存在相同数值的节点
样例
给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

2
/
1 3
题目链接:http://www.lintcode.com/zh-cn/problem/construct-binary-tree-from-preorder-and-inorder-traversal/

和上一道题,已知后序和中序的道理一样,用递归来做,只要找好递归的分割点就可以了。这里说明一下,如果已知前序遍历和后序遍历,是不能唯一确定一颗二叉树的。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
 

class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        // write your code here
        if (preorder.size() == 0) return NULL;
        return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
    }
    TreeNode *build(vector<int> &preorder,vector<int> &inorder,int startpre,int endpre,int startin,int endin) {
        if (startpre > endpre || startin > endin) return NULL;
        TreeNode *root = new TreeNode(preorder[startpre]);
        int divide = 0;
        while (divide <= endin && inorder[divide] != root->val) divide++;
        int offset = divide - startin - 1;
        root->left = build(preorder,inorder,startpre + 1,startpre + 1 + offset,startin,startin + offset);
        root->right = build(preorder,inorder,startpre + offset + 2,endpre,divide + 1,endin);
        return root;
    }
};
    原文作者:yzawyx0220
    原文地址: https://www.jianshu.com/p/93097a115523
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞