首页 > 代码库 > leetcode Convert Sorted Array to Binary Search Tree

leetcode Convert Sorted Array to Binary Search Tree

利用更有序数组,构造平衡二叉树。

思路,递归,每次中间节点为根节点,然后递归获得左右子树。

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode *fun(vector<int> &num, int start, int end)    {        if (start > end) return NULL;        int mid = (start + end) / 2;        TreeNode *root = new TreeNode(num[mid]);                root -> left = fun(num, start, mid - 1);        root -> right = fun(num, mid + 1, end);        return root;    }    TreeNode *sortedArrayToBST(vector<int> &num) {        return fun(num, 0, num.size() - 1);    }};

 

leetcode Convert Sorted Array to Binary Search Tree