108. 将有序数组转换为二叉搜索树 - 力扣(LeetCode)
每次将数组对半分,数组的中点作为树的节点
先选择整个数组的中点作为根节点,然后选择对半分后的两个子数组的中点作为根节点的左右节点…
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insert(vector<int> &num, int l, int r) {
if (l > r) return nullptr;
int mid = (l + r) / 2;
TreeNode *node = new TreeNode(num[mid]);
node->left = insert(num, l, mid - 1);
node->right = insert(num, mid + 1, r);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return insert(nums, 0, nums.size() - 1);
}
};
543. 二叉树的直径 - 力扣(LeetCode)
直径可以理解为:左节点的最大深度+右节点的最大深度
搜索树中所有节点的直径,找到最大的即可
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int ans = 0;
int dfs(TreeNode *cur) {
if (cur == nullptr) return 0;
int l = dfs(cur->left);
int r = dfs(cur->right);
ans = max(ans, l + r);
return 1 + max(l, r);
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans;
}
};