题:
给定一个二叉树根国彩网和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