在C语言中,打印给定层级的叶节点
The task involves printing leaf nodes of a binary tree at given level k which is specified by the user.
Leaf nodes are the end nodes whose left and right pointer is NULL which means that particular node is not a parent node.
Example
Input : 11 22 33 66 44 88 77 Output : 88 77登录后复制
在这里,k代表需要打印的树的层级。这里使用的方法是遍历每个节点,并检查节点是否有任何指针。即使只有一个指针,表示左侧或右侧或两者都有,那个特定的节点也不能是叶节点。
使用层次遍历技术递归遍历每个节点,从左侧开始,然后是根节点,最后是右侧。
下面的代码展示了给定算法的C语言实现
算法
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *left, *right Step 2 -> create function for inserting node with parameter as new_data Declare temp variable of node using malloc Set temp->data = new_data Set temp->left = temp->right = NULL return temp Step 3 -> declare Function void leaf(struct node* root, int level) IF root = NULL Exit End IF level = 1 IF root->left == NULL && root->right == NULL Print root->data End End ELSE IF level>1 Call leaf(root->left, level - 1) Call leaf(root->right, level - 1) End Step 4-> In main() Set level = 4 Call New passing value user want to insert as struct node* root = New(1) Call leaf(root,level) STOP登录后复制