[面試題]找BST中的第K大結點

上次參加微信一面的筆試中的最後一道。當時考慮了遞歸,覺得效率不好,猶豫中沒做完,不甘心所以回學校又寫了一遍。主要使用棧,核心代碼特別簡單。如圖:

 

完整的源碼如下:

#include <iostream>
using namespace std;

struct Node
{
	int value;
	Node * left;
	Node * right;
};
struct BST
{
	Node * root;
};
void insert_tree(Node * root,Node * node)
{
	if(root == 0 || node == 0)
		return;
	Node * pos = root;
	Node * parent = root;
	while(pos != 0)
	{
		parent = pos;
		if(node->value < pos->value)
		{
			pos = pos->left;
		}else
		{
			pos = pos->right;
		}
	}
	//insert left
	if(node->value < parent->value)
	{
		parent->left = node;
	}else//insert right
	{
		parent->right = node;
	}

};
//preorder traverse the tree
void print_tree(Node * root)
{
	if(root == 0)
		return;
	cout << root->value << " ";
	print_tree(root->left);
	print_tree(root->right);
}
void destroy_tree(Node * root)
{
	if(root == 0)
		return;
	destroy_tree(root->left);
	destroy_tree(root->right);
	delete root;
}
int main()
{
	cout << "Input the number of node in the BST: ";
	int nodes;
	cin >> nodes;
	BST bst;//create a binary search tree
	bst.root = 0;
	cout << "Input the nodes: " << endl;
	for(int i = 0;i < nodes;i++)
	{
		Node * node = new Node;
		cin >> node->value;
		node->left = 0;
		node->right = 0;
		if(bst.root == 0)
		{
			bst.root = node;
			continue;
		}
		insert_tree(bst.root,node);
	}
	print_tree(bst.root);
	cout << endl;
	int kth = 0;
	cout << "Input the kth: ";
	cin >> kth;
	if(kth <= 0 || kth > nodes)
	{
		cout << "Input Error!" << endl;
		return -1;
	}
	//find the kth node, then print it
	Node * pos = bst.root;
	Node ** stack = new Node*[nodes];
	//the top of stack
	int top = 0;	
	while(kth > 0)
	{
		if(pos != 0)
		{
			//push
			 stack[top] = pos;
			top++;
			pos = pos->right;
		}else
		{
			//pop
			top--;
			kth--;
			//go to the left child
			pos = stack[top]->left;
		}
	}
	//print the kth max value
	cout << stack[top]->value << endl;

	//free the memory
	destroy_tree(bst.root);
	delete [] stack;

	system("pause");
	return 0;

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章