首页 > 文章列表 > 在C语言中打印二叉树的左视图

在C语言中打印二叉树的左视图

二叉树 打印 左视图
291 2023-09-04

任务是打印给定二叉树的左节点。首先,用户将插入数据,从而生成二叉树,然后打印所形成的树的左视图。

每个节点最多可以有 2 个子节点,因此这里程序必须仅遍历与节点关联的左指针< /p>

如果左指针不为空,则意味着它将有一些与之关联的数据或指针,否则它将是要打印并显示为输出的左子级。

示例< /h2>
Input : 1 0 3 2 4
Output : 1 0 2

在C语言中打印二叉树的左视图

这里,橙色节点代表二叉树的左视图。

在给定的图中,数据为 1 的节点是根节点,因此它将被打印,而不是转到左子节点,它将打印 0,然后它将转到 3 并打印其左子节点,即 2。

我们可以使用递归方法来存储节点的级别并重复转移到

下面的代码显示了给定算法的 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 left_view(struct node* root, int level, int* highest_level)
      IF root = NULL
         Exit
      End
      IF *highest_level < level
         Print root->data
         Set *highest_level = level
      End
      Recursively call left_view(root->left, level + 1, highest_level)
      Recursively call left_view(root->right, level + 1, highest_level)
   Step 4 -> Declare Function void left(struct node* root)
      Set int highest_level = 0
      Call left_view(root, 1, &highest_level)
   Step 5-> In main()
      Call New passing value user want to insert as struct node* root = New(1)
      Call left(root)
STOP

示例

#include <stdio.h>
#include <stdlib.h>
//create a structure of a node
struct node {
   int data;
   struct node *left, *right; //this pointer will point to the nodes attached with a node
};
struct node* New(int new_data) {
   struct node* temp = (struct node*)malloc(sizeof(struct node));
   //allocating memory to a pointer    dynamically
   temp->data = new_data;
   temp->left = temp->right = NULL;
   return temp;
}
void left_view(struct node* root, int level, int* highest_level) {
   if (root == NULL) //if there is no node that means no data
   return;
   // this function will retrun the root node if there is only root node in a tree
   if (*highest_level < level) {
      printf("%dt", root->data);
      *highest_level = level;
   }
   // Recursive function
   left_view(root->left, level + 1, highest_level);
   left_view(root->right, level + 1, highest_level);
}
void left(struct node* root) {
   int highest_level = 0;
   left_view(root, 1, &highest_level);
}
int main() {
   printf("left view of a binary tree is : ");
   struct node* root = New(1);
   root->left = New(0);
   root->right = New(3);
   root->right->left = New(2);
   root->right->right = New(4);
   left(root);
   return 0;
}

输出

如果我们运行上面的程序,它将生成以下输出。

left view of a binary tree is : 1 0 2