可能我绕的很笨,这个思路很差劲,就是用链表存储 然后升序排列 然后折半那样构建bst 然后直接Max函数返回深度。但是 排序,控制输入 主函数那里,就没有写了。能不能麻烦按照这个思路补全一下,对不起,具体输入输出样例在图片上
#include
#include
using namespace std;
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) {}
};
int maxDepth(TreeNode root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
struct ListNode
{
int val;
ListNode* next;
};
ListNode* Creat();
struct ListNode* Creat()
{
int n;
struct ListNode* head = 0, * p, * t = 0;
while (cin >> n) {
p = new ListNode;
p->val = n;
p->next = 0;
if (head == 0) {
head = p;
t = head;
}
else {
t->next = p;
t = p;
}
char ch = cin.get();
if (ch == '\n')
break;
}
return head;
}
ListNodesort(ListNodehead){}
ListNode* getMedian(ListNode* left, ListNode* right) {
ListNode* fast = left;
ListNode* slow = left;
while (fast != right && fast->next != right) {
fast = fast->next;
fast = fast->next;
slow = slow->next;
}
return slow;
}
TreeNode* buildTree(ListNode* left, ListNode* right) {
if (left == right) {
return nullptr;
}
ListNode* mid = getMedian(left, right);
TreeNode* root = new TreeNode(mid->val);
root->left = buildTree(left, mid);
root->right = buildTree(mid->next, right);
return root;
}
int main()
{
}
你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答
本次提问扣除的有问必答次数,已经为您补发到账户,我们后续会持续优化,扩大我们的服务范围,为您带来更好地服务。