cpp-algo-cases/chapter_tree/binary_tree.cpp

44 lines
944 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: binary_tree.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Driver Code */
int main() {
/* <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
// <20><>ʼ<EFBFBD><CABC><EFBFBD>ڵ<EFBFBD>
TreeNode *n1 = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
// <20><><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD>֮<EFBFBD><D6AE><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ã<EFBFBD>ָ<EFBFBD>
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
cout << endl << "<EFBFBD><EFBFBD>ʼ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>\n" << endl;
printTree(n1);
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɾ<EFBFBD><C9BE><EFBFBD>ڵ<EFBFBD> */
TreeNode *P = new TreeNode(0);
// <20><> n1 -> n2 <20>м<EFBFBD><D0BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD> P
n1->left = P;
P->left = n2;
cout << endl << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD> P <20><>\n" << endl;
printTree(n1);
// ɾ<><C9BE><EFBFBD>ڵ<EFBFBD> P
n1->left = n2;
delete P; // <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
cout << endl << "ɾ<EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD> P <20><>\n" << endl;
printTree(n1);
// <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
freeMemoryTree(n1);
return 0;
}