首页 > 代码库 > 根据前序遍历和中序遍历树构造二叉树

根据前序遍历和中序遍历树构造二叉树

根据前序遍历和中序遍历树构造二叉树

样例:

给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

  2

 /  \

1  3

我们知道前序遍历是中->左->右,中序遍历是左->中->右。因此根据前序遍历的第一个数,即为根节点,我们可以在中序遍历中找到根节点的左子树和右子树,同样递归在左子树中找到左子树的根节点和其左右子树,对右子树也一样。这样理清思路后代码就不难写出来了。

/**
 * 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 *construct(vector<int> &preorder, vector<int> &inorder, int ps, 
        int pe, int is, int ie) {
            TreeNode * root = new TreeNode(preorder[ps]);
            if (ps == pe) return root;
            int i;
            for (i = 0; i < ie; i++) {   
                if (inorder[i] == root->val) break;   //找到根节点位置
            }
            //递归构造左右子树
            if (is <= i-1) 
                root->left = construct(preorder, inorder, 
                    ps+1, ps+(i-is), is, i-1);
            if (i+1 <= ie) 
                root->right = construct(preorder, inorder,
                    ps+(i-is)+1, pe, i+1, ie);
            return root;
        }

    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if (preorder.empty() || inorder.empty() || 
            preorder.size() != inorder.size()) return NULL;
        return construct(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
    }
};

 

根据前序遍历和中序遍历树构造二叉树