Double Tree与C ++程序中的示例

在本教程中,我们将学习如何将给定的树加倍。

让我们看看解决问题的步骤。

  • 创建节点类。

  • 用伪数据初始化树。

  • 编写一个递归函数以将树加倍。

    • 递归地遍历树。

    • 将左节点存储在变量中。

    • 遍历后,通过创建新节点添加数据。

    • 现在,将左节点作为左子节点添加到新创建的节点中。

  • 打印树。

示例

让我们看一下代码。

#include <bits/stdc++.h>
using namespace std;
class node {
   public:
   int data;
   node* left;
   node* right;
};
node* newNode(int data) {
   node* Node = new node();
   Node->data = data;
   Node->left = NULL;
   Node->right = NULL;
   return Node;
}
void doubleTree(node* Node) {
   node* oldLeft;
   if (Node == NULL) return;
      doubleTree(Node->left);
   doubleTree(Node->right);
   oldLeft = Node->left;
   Node->left = newNode(Node->data);
   Node->left->left = oldLeft;
}
void printTree(node* node) {
   if (node == NULL) {
      return;
   }
   printTree(node->left);
   cout << node->data << " ";
   printTree(node->right);
}
int main() {
   node *root = newNode(1);
   root->left = newNode(2);
   root->right = newNode(3);
   cout << "Original Tree" << endl;
   printTree(root);
   cout << endl;
   doubleTree(root);
   cout << "Double Tree" << endl;
   printTree(root);
   cout << endl;
   return 0;
}
输出结果

如果运行上面的代码,则将得到以下结果。

Original Tree
2 1 3
Double Tree
2 2 1 1 3 3

结论