【问题标题】:Leetcode 108. Convert Sorted Array to Binary Search TreeLeetcode 108. 将排序数组转换为二叉搜索树
【发布时间】:2020-12-28 20:33:36
【问题描述】:

我的代码:

class Solution {
    public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* head = NULL;
        helper(head, 0, nums.size()-1, nums);
        return head;
    }
    
    void helper(TreeNode* node, int left, int right, vector<int> nums) {
        if(left>right) 
            return ;
        int mid = (left+right)/2;
        TreeNode* temp = new TreeNode(nums[mid]);
        node = temp;
        helper(temp->left, left, mid-1, nums);
        helper(temp->right, mid+1, right, nums);
    }
};

这会为所有情况输出“[]”。我看到了一些返回 TreeNode 指针的递归解决方案,并想尝试不同的解决方案。 我在这里想念什么?谢谢。

【问题讨论】:

  • 分配给函数的(非引用)参数在该函数之外没有任何影响。指针没有什么特别之处。
  • 顺便说一句,use nullptr for pointers
  • @molbdnilo 但由于我将指针传递给节点,它们不是通过引用传递吗?
  • 如果你想要一个函数来改变 int 变量中的内容,你可以传递一个指向它的指针 int * 。如果您希望函数更改 TreeNode* 变量中的内容,请将指针传递给它 TreeNode**
  • @PranavVA 您正在按值传递指针。如果指针有效,你可以修改它指向的节点,但你永远不能改变它指向的 which 节点。

标签: c++ recursion binary-search-tree


【解决方案1】:

快到了!我们可以使用 const_iterator 并使用非 void 助手解决问题:

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>

using ValueType = int;
using Iterator = std::vector<ValueType>::const_iterator;

static const struct Solution {
    TreeNode* sortedArrayToBST(
        const std::vector<ValueType>& nums
    ) {
        if (nums.empty()) {
            return nullptr;
        }

        return buildBinarySearchTree(std::begin(nums), std::end(nums));
    }

    TreeNode* buildBinarySearchTree(
        const Iterator lo, 
        const Iterator hi
    ) {
        if (lo >= hi) {
            return nullptr;
        }

        Iterator mid = lo + (hi - lo) / 2;
        TreeNode* root = new TreeNode(*mid);
        root->left = buildBinarySearchTree(lo, mid);
        root->right = buildBinarySearchTree(mid + 1, hi);
        return root;
    }
};

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多