C++中列印給定節點在二叉樹中的堂兄弟節點


二叉樹是一種特殊的樹,其每個節點最多有兩個子節點。因此,每個節點要麼是葉節點,要麼有一個或兩個子節點。

示例:

在這個問題中,我們給定一個二叉樹和樹的一個節點,我們必須找到該節點的堂兄弟節點。二叉樹中不應列印兄弟節點。

讓我們舉個例子:

對於上面的二叉樹,堂兄弟節點是 5。

為了使概念更清晰,讓我們描述一下堂兄弟節點。在二叉樹中,如果兩個節點位於二叉樹的同一層(深度),但沒有相同的父節點,則稱這兩個節點為堂兄弟節點。

現在,讓我們為這個問題建立一個解決方案。

在這裡,我們必須列印節點同一層的所有節點,即所有與根節點距離相同的節點。但是,我們必須排除與該節點本身具有相同父節點的節點。為此,我們將首先找到節點的層級,然後列印所有節點(節點本身和具有相同父節點的節點除外)。

示例

現在,讓我們根據此邏輯建立一個程式:

#include <bits/stdc++.h>
using namespace std;
struct Node{
   int data;
   Node *left, *right;
};
Node *newNode(int item){
   Node *temp = new Node;
   temp->data = item;
   temp->left = temp->right = NULL;
   return temp;
}
int levelOfNode(Node *root, Node *node, int level){
   if (root == NULL)
      return 0;
   if (root == node)
      return level;
   int downlevel = levelOfNode(root->left,
   node, level + 1);
   if (downlevel != 0)
      return downlevel;
   return levelOfNode(root->right, node, level + 1);
}
void printCousin(Node* root, Node *node, int level){
   if (root == NULL || level < 2)
      return;
   if (level == 2){
      if (root->left == node || root->right == node)
         return;
      if (root->left)
         cout << root->left->data << " ";
      if (root->right)
         cout << root->right->data;
   }
   else if (level > 2){
      printCousin(root->left, node, level - 1);
      printCousin(root->right, node, level - 1);
   }
}
void cousinNode(Node *root, Node *node){
   int level = levelOfNode(root, node, 1);
   printCousin(root, node, level);
}
int main(){
   Node *root = newNode(11);
   root->left = newNode(15);
   root->right = newNode(4);
   root->left->left = newNode(3);
   root->left->right = newNode(7);
   root->left->right->right = newNode(9);
   root->right->left = newNode(17);
   root->right->right = newNode(8);
   root->right->left->right = newNode(5);
   cout<<”The cousin nodes are : \t”
   cousinNode(root, root->right->right);
   return 0;
}

輸出

The cousin nodes are : 3 7

更新於:2020年1月3日

190 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告