首先两两比较找到最大的元素,需要n-1次,即二叉树的非叶子节点的个数。之后次最大的一定在和最大的元素比较过的元素中,共有lgn-1个,即树的高度。故加起来就是n+lgn-2
#include<iostream> using namespace std; class Node { public: Node(); Node(int d); Node*left; Node*right; int data; }; Node::Node() { right = left = NULL; } Node::Node(int d) { data = d; right = left = NULL; } class BinaryTree { public: Node*root; void create_tree(Node**node,int len); int min(int a, int b); int search_second_small(); BinaryTree(); }; BinaryTree::BinaryTree() { root = new Node(); } int BinaryTree::min(int a, int b) { return a < b ? a : b; } void BinaryTree::create_tree(Node**node, int len) { if (len < 2) return; if (len == 2) { root->left = node[0]; root->right = node[1]; root->data = min(node[0]->data,node[1]->data); } else { int new_len = (len % 2) ? (len / 2 + 1) : (len / 2); Node**new_node = new Node*[new_len]; int mod = len % 2; for (int i = 0; i < new_len - mod; i++) { new_node[i] = new Node(min(node[2*i]->data,node[2*i+1]->data)); new_node[i]->left = node[2 * i]; new_node[i]->right = node[2 * i + 1]; } if (mod) new_node[new_len - 1] = node[len-1]; create_tree(new_node, new_len); delete[] new_node; } } int BinaryTree::search_second_small() { Node*p = root; int second = 0x7fffffff; while (p->left&&p->right) { if (p->data == p->left->data) { if (second > p->right->data) second = p->right->data; p = p->left; } else { if (second > p->left->data) second = p->left->data; p = p->right; } } return second; } int main() { int arr[] = {1,3,2,4,6,0,9,8}; int N = sizeof arr / sizeof arr[0]; Node**node = new Node*[N]; for (int i = 0; i < N; i++) node[i] = new Node(arr[i]); BinaryTree* bi_tree = new BinaryTree(); bi_tree->create_tree(node, N); cout << bi_tree->root->data << endl; cout << bi_tree->search_second_small() << endl; return 0; }
时间: 2024-10-13 01:33:51