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
结论
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短