用 C 語言列印二叉樹的右檢視


任務是列印給定二叉樹的右節點。首先,使用者將插入資料以建立二叉樹,然後列印所形成樹的右檢視。

上圖展示了用節點 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 實現

演算法

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

示例

#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

更新於: 2019年8月22日

321 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.