前序遍历重构二叉树
思路
- 整个二叉树用数组存储
- 因为先序遍历它先遍历根,再遍历左,左边没有跑完是不会去遍历右边的,所以遍历左子树,就是数组元素每回向后一个,个数-1
- 遍历右边时,就是数组起始位置+左子树跑到的位置+每次往后走一个,大小就是减去左子树用掉的个数+每回个数-1
- 因为要返回遍历的位置,和遍历用掉的个数,所以每回都要返回两个值,用结构体返回。
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct TreeNode
{struct TreeNode *left;struct TreeNode *right;char val;
}TreeNode;typedef struct Result{TreeNode * root; //构建的树的根结点int used; //构建过程中用掉的val个数
} Result;Result CreateTree(char preorder[], int size){if (size == 0){Result result;result.root = NULL;result.used = 0;return result;}char rootVal = preorder[0];if (rootVal == '#'){Result result;result.root = NULL;result.used = 1; //'#'号在数组中也占一个位置return result;}//根的过程TreeNode * root = (TreeNode *)malloc(sizeof(TreeNode));root->val = rootVal;root->left = root->right = NULL;//左子树Result left_result = CreateTree(preorder + 1, size - 1);//右子树Result right_result = CreateTree(preorder + 1 + left_result.used, size - 1 - left_result.used);root->left = left_result.root;root->right = right_result.root;Result result;result.root = root;result.used = 1 + left_result.used + right_result.used;return result;
}void InorderTraversal(TreeNode * root){if (root == NULL){return;}InorderTraversal(root->left);printf("%c", root->val);printf(" ");InorderTraversal(root->right);
}void TestCreateTree()
{char preorder[200];scanf("%s", preorder);int size = strlen(preorder);Result result = CreateTree(preorder, size);InorderTraversal(result.root);
}int main()
{TestCreateTree();return 0;
}
求二叉树中所有结点的个数
思路
遍历整棵树,不是空结点,个数就++
void TreeSize(TreeNode *root, int *size){if (root == NULL){return;}(*size)++;TreeSize(root->left,size);TreeSize(root->right,size);}
思路2
根+左结点个数+右结点个数
int TreeSize2(TreeNode *root){if (root == NULL){return 0;}return 1 + TreeSize2(root->left) + TreeSize2(root->right);
}