首頁  >  文章  >  後端開發  >  在C語言中列印二元樹的左視圖

在C語言中列印二元樹的左視圖

WBOY
WBOY轉載
2023-09-03 13:25:051327瀏覽

任務是列印給定二元樹的左節點。首先,使用者將插入數據,從而生成二元樹,然後列印所形成的樹的左側視圖。

每個節點最多可以有2 個子節點,因此這裡程式必須只遍歷與節點關聯的左指標

如果左指標不為空,則表示它將有一些與之關聯的資料或指針,否則它將是要列印並顯示為輸出的左子級。

範例
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("%d\t", 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

以上是在C語言中列印二元樹的左視圖的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除