leetcode 先序遍历构造二叉树 -- 递归

返回与给定先序遍历 preorder 相匹配的二叉搜索树(binary search tree)的根结点。

(回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left 的任何后代,值总< node.val,而 node.right 的任何后代,值总> node.val。此外,先序遍历首先显示节点的值,然后遍历node.left,接着遍历 node.right。)

示例:

输入:[8,5,1,7,10,12]
输出:[8,5,10,1,7,null,12]


image.png

先序遍历是先遍历根结点,再遍历左子树,最后遍历右子树。左子树的结点都会小于根结点,右子树的结点都会大于根结点。因此先找到左子树与右子树的分界点,再分别递归建立左子树和右子树。

class Solution {
public:
    int find_lower_bound(vector preorder, int cur){
        int lower_bound = cur;
        for(int i=cur+1;i preorder, int cur,int right_bound){
        int lower_bound = find_lower_bound(preorder, cur);
        TreeNode* root = new TreeNode(preorder[cur]);
        if(cur < lower_bound){
            root->left = bst(preorder, cur+1, lower_bound);
        }
        if(lower_bound < right_bound){
            root->right = bst(preorder, lower_bound+1, right_bound);
        }
        return root;
    }
    TreeNode* bstFromPreorder(vector& preorder) {
        return bst(preorder,0,preorder.size()-1);
    }
};

题目链接:https://leetcode-cn.com/problems/construct-binary-search-tree-from-preorder-traversal/

你可能感兴趣的:(leetcode 先序遍历构造二叉树 -- 递归)