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
结论
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短