给定元素x,任务是找到其紧邻的较小元素的值。
例子 :
Input : x = 30 (for above tree)
Output : Immediate smaller element is 25
说明:元素2、15、20和25小于x,即30,但25是紧邻的较小元素,因此是答案。
方法 :
- 令res为结果节点。
- 将结果节点初始化为NULL。
- 对于每个节点,检查root的数据是否大于res,但小于x。如果是,请更新资源。
- 递归地对给定泛型树的所有节点执行相同的操作。
- 返回res,而res-> key将是紧邻的较小元素。
下面是上述方法的实现:
// C++ program to find immediate Smaller
// Element of a given element in a n-ary tree.
#include
using namespace std;
// class of a node of an n-ary tree
class Node {
public:
int key;
vector child;
// constructor
Node(int data)
{
key = data;
}
};
// Function to find immediate Smaller Element
// of a given number x
void immediateSmallerElementUtil(Node* root,
int x, Node** res)
{
if (root == NULL)
return;
// if root is greater than res, but less
// than x, then update res
if (root->key < x)
if (!(*res) || (*res)->key < root->key)
*res = root; // Updating res
// Number of children of root
int numChildren = root->child.size();
// Recursive calling for every child
for (int i = 0; i < numChildren; i++)
immediateSmallerElementUtil(root->child[i], x, res);
return;
}
// Function to return immediate Smaller
// Element of x in tree
Node* immediateSmallerElement(Node* root, int x)
{
// resultant node
Node* res = NULL;
// calling helper function and using
// pass by reference
immediateSmallerElementUtil(root, x, &res);
return res;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = new Node(20);
(root->child).push_back(new Node(2));
(root->child).push_back(new Node(34));
(root->child).push_back(new Node(50));
(root->child).push_back(new Node(60));
(root->child).push_back(new Node(70));
(root->child[0]->child).push_back(new Node(15));
(root->child[0]->child).push_back(new Node(20));
(root->child[1]->child).push_back(new Node(30));
(root->child[2]->child).push_back(new Node(40));
(root->child[2]->child).push_back(new Node(100));
(root->child[2]->child).push_back(new Node(20));
(root->child[0]->child[1]->child).push_back(new Node(25));
(root->child[0]->child[1]->child).push_back(new Node(50));
int x = 30;
cout << "Immediate smaller element of " << x << " is ";
cout << immediateSmallerElement(root, x)->key << endl;
return 0;
}
输出 :
Immediate smaller element of 30 is 25
时间复杂度: O(N),其中N是N元树中的节点数。
辅助空间: O(N),用于递归调用(最坏的情况是一个节点有N个子节点)