ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

检查给定的两个国彩网是否在二叉树中彼此兄弟

前开发者教程 2020年10月8日

题:

给定一个二叉树根国彩网和2个国彩网值,请检查这2个国彩网是否为兄弟国彩网。

解:

二元树

如果我们将国彩网值发送为7和15,则它们是同级

如果我们将国彩网值发送为7和18,则它们不是同级。

因此,这里的解决方案是,每个国彩网最多可以有2个子国彩网。

因此,请检查每个国彩网的子国彩网,并检查其是否匹配。

如果匹配,则返回true,否则返回false。

C ++解决方案

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

bool are_siblings(Node *node, int a, int b) 
{
    if (node == NULL) 
    {
      return false;
    }

    return (node->left->data == a && node->right->data == b) 
        || (node->left->data == b && node->right->data == a)
        || are_siblings(node->left, a, b)
        || are_siblings(node->right, a, b);
  }
int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    int child_1 = 7;
    int child_2 = 15;

    if (are_siblings(root, child_1, child_2))
    {
        cout<<child_1<< " and "<<child_2<<" are siblings "<<endl;
    } else {
        cout<<child_1 <<" and "<<child_2<<" are NOT siblings "<<endl;
    }

    return 0;  
}  

 

输出:

7 and 15 are siblings
分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的





        <progress class="GpnnAqD"><rp id="IGiEUtq" class="I5Xz9UC"></rp></progress>


          <base id="ItKFSLN"><frameset id="Ts5TBVB" class="T0FYnJn"><q class="yjaAqKE"></q></frameset></base>