105. 从前序与中序遍历序列构造二叉树

  • 题目
  • 算法设计:深度优先搜索



 


题目

传送门:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

105. 从前序与中序遍历序列构造二叉树_leetcode


 


算法设计:深度优先搜索

构造二叉树,第一件事一定是找根节点,然后想办法构造左右子树。

前序遍历的特点是, 根节点出现在数组的第一位,而中序遍历中根节点出现在数组的中间位置。

所以我们只需要根据先序遍历得到根节点,然后在中序遍历中找到根节点的位置,它的左边就是左子树的节点,右边就是右子树的节点。

生成左子树和右子树就可以递归的进行了。

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return build(preorder, inorder, 0, 0, inorder.size()-1);
    }
    
    TreeNode* build(vector<int>& preorder, vector<int>& inorder, int& rootIdx, int left, int right) {
        if (left > right) return NULL;
        int pivot = left;
        while(inorder[pivot] != preorder[rootIdx]) pivot++;                  // 在中序遍历中,找到根节点的下标
        
        rootIdx++;                                                           // 前序遍历,根节点下标更新
        TreeNode* newNode = new TreeNode(inorder[pivot]);                    // 构造二叉树的根节点
        newNode->left = build(preorder, inorder, rootIdx, left, pivot-1);    // 构造二叉树的左子节点
        newNode->right = build(preorder, inorder, rootIdx, pivot+1, right);  // 构造二叉树的右子节点
        return newNode;
    }
};