博客
关于我
数据结构 二叉树有遍历的想法
阅读量:502 次
发布时间:2019-03-07

本文共 2385 字,大约阅读时间需要 7 分钟。

#include 
#include
using namespace std;#define LEN 30typedef struct TreeNode { int data; TreeNode *LChild; TreeNode *RChild;} TreeNode;TreeNode* init(int* init_arr, int lens) { TreeNode* treeArr[LEN]; for (int i = 0; i < lens; i++) { if (init_arr[i] != 0) { treeArr[i] = (TreeNode*)malloc(sizeof(TreeNode)); treeArr[i]->data = init_arr[i]; treeArr[i]->LChild = NULL; treeArr[i]->RChild = NULL; } else { treeArr[i] = NULL; } } int len = lens / 2; for (int i = 0; i < len; i++) { if (treeArr[i] != NULL) { treeArr[i]->LChild = treeArr[2*i + 1]; treeArr[i]->RChild = treeArr[2*i + 2]; } } return treeArr[0];}void PreOrder(TreeNode* head) { if (head != NULL) { cout << head->data << " "; PreOrder(head->LChild); PreOrder(head->RChild); }}void InOrder(TreeNode* head) { if (head != NULL) { InOrder(head->LChild); cout << head->data << " "; InOrder(head->RChild); }}void PostOrder(TreeNode* head) { if (head != NULL) { PostOrder(head->LChild); PostOrder(head->RChild); cout << head->data << " "; }}void print_leaf_node(TreeNode* root) { if (root != NULL) { if (root->LChild == NULL && root->RChild == NULL) { cout << root->data << " "; } print_leaf_node(root->LChild); print_leaf_node(root->RChild); }}int Leaf_count = 0;void leaf_num1(TreeNode* root) { if (root != NULL) { leaf_num1(root->LChild); leaf_num1(root->RChild); if (root->LChild == NULL && root->RChild == NULL) { Leaf_count++; } }}int leaf_num2(TreeNode* root) { if (root == NULL) { return 0; } else if (root->LChild == NULL && root->RChild == NULL) { return 1; } else { return leaf_num2(root->LChild) + leaf_num2(root->RChild); }}int depth = 0;void Pre_tree_depth(TreeNode* head, int h) { if (head != NULL) { if (h > depth) { depth = h; } Pre_tree_depth(head->LChild, h + 1); Pre_tree_depth(head->RChild, h + 1); }}int main(int argc, char const* argv[]) { TreeNode* head = (TreeNode*)malloc(sizeof(TreeNode)); int init_arr[] = {1, 2, 3, 0, 4, 0, 5}; head = init(init_arr, 7); PreOrder(head); cout << endl;}

转载地址:http://ncccz.baihongyu.com/

你可能感兴趣的文章
Python:函数进阶
查看>>
Python:在整数的二进制表示中查找最长的二进制间隙
查看>>
Python:如何从二进制转换为 base 64 并返回?
查看>>
Python:如何以非阻塞方式读取子进程的标准输出
查看>>
Python:如何使用 plotly 制作阴影区域或交替背景颜色?
查看>>
Python:如何根据日期时间获取值的计数
查看>>
python:如何检测串行 COM 上的设备名称/ID
查看>>
Python:如何模拟 datetime.utcnow()?
查看>>
Python:如果DataFrames之间的其他值匹配,则对DataFrame中的值求和
查看>>
Python:字典思维
查看>>
Python:将 HEX 字符串转换为字节
查看>>
Python:将列表与范围列表合并
查看>>
Python:将列表列表初始化为一定大小,
查看>>
Python:带有生成器的给定集合的幂集
查看>>
Python:按字符的位置拆分字符串
查看>>
Python:替换嵌套字典中的值
查看>>
Python:爬取数据出现response.status_code为403解决方法
查看>>
Python:爬取数据出现response.status_code为418解决方法
查看>>
Python:生成“元组集“;来自“元组列表“;不考虑顺序
查看>>
Python:生成具有趋势的随机时间序列数据(例如周期性、指数衰减等)
查看>>