任务是打印给定二叉树的右节点。首先用户将插入数据以创建二叉树,然后打印所形成的树的右视图。
上图展示了使用节点10、42、93、14、35、96、57和88创建的二叉树,其中选择并显示在树的右侧的节点。例如,10、93、57和88是二叉树的最右节点。
示例input : 10 42 93 14 35 96 57 88output : 10 93 57 88
每个节点都有两个指针,即左指针和右指针。根据这个问题,程序只需遍历右节点。因此,不需要考虑节点的左子节点。
右视图存储了所有那些是其所在层级的最后一个节点的节点。因此,我们可以简单地使用递归方法以这样的方式存储和访问节点,即先遍历右子树再遍历左子树。每当程序检测到节点的层级大于前一个节点的层级时,前一个节点被显示出来,因为它将是其所在层级的最后一个节点。
下面的代码展示了给定算法的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 item declare temp variable of node using malloc set temp->data = item set temp->left = temp->right = null return temp step 3 -> declare function void right_view(struct node *root, int level, int *end_level) if root = null return if *end_level < level print root->data set *end_level = level call right_view(root->right, level+1, end_level) call right_view(root->left, level+1, end_level) step 4 -> declare function void right(struct node *root) set int level = 0 call right_view(root, 1, &level) step 5 -> in main() pass the values for the tree nodes using struct node *root = new(10) call right(root)stop
example的中文翻译为:示例#include<stdio.h>#include<stdlib.h>struct node { int data; struct node *left, *right;};struct node *new(int item) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = item; temp->left = temp->right = null; return temp;}void right_view(struct node *root, int level, int *end_level) { if (root == null) return; if (*end_level < level) { printf("%d\t", root->data); *end_level = level; } right_view(root->right, level+1, end_level); right_view(root->left, level+1, end_level);}void right(struct node *root) { int level = 0; right_view(root, 1, &level);}int main() { printf("right view of a binary tree is : "); struct node *root = new(10); root->left = new(42); root->right = new(93); root->left->left = new(14); root->left->right = new(35); root->right->left = new(96); root->right->right = new(57); root->right->left->right = new(88); right(root); return 0;}
输出如果我们运行上面的程序,它将生成以下输出。
right view of a binary tree is : 10 93 57 88
以上就是在c语言中,将二叉树的右视图打印出来的详细内容。