任务是打印给定二叉树的右节点。首先用户将插入数据以创建二叉树,然后打印所形成的树的右视图。

上图展示了使用节点10、42、93、14、35、96、57和88创建的二叉树,其中选择并显示在树的右侧的节点。例如,10、93、57和88是二叉树的最右节点。
示例
Input : 10 42 93 14 35 96 57 88 Output : 10 93 57 88
每个节点都有两个指针,即左指针和右指针。根据这个问题,程序只需遍历右节点。因此,不需要考虑节点的左子节点。
右视图存储了所有那些是其所在层级的最后一个节点的节点。因此,我们可以简单地使用递归方法以这样的方式存储和访问节点,即先遍历右子树再遍历左子树。每当程序检测到节点的层级大于前一个节点的层级时,前一个节点被显示出来,因为它将是其所在层级的最后一个节点。
立即学习“C语言免费学习笔记(深入)”;
下面的代码展示了给定算法的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)
STOPExample
的中文翻译为:示例
#include#include 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











