T4、判断一棵树是否是另一颗树的子树
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if (NULL == p && NULL == q)
return true;
if (NULL == p || NULL == q)
return false;
if (p->val != q->val)
return false;
return isSameTree(p->left, q->left)
&& isSameTree(p->right, q->right);
}
bool isSubTree(struct TreeNode* root, struct TreeNode* subRoot)
{
if (NULL == root)
return false;
if (isSameTree(root, subRoot))
return true;
return isSubTree(root->left, subRoot)
|| isSubTree(root->right, subRoot);
}
T5、二叉树的前序遍历,并保存在一个动态数组中
int TreeSize(struct TreeNode* root)
{
if (NULL == root)
{
return 0;
}
return TreeSize(root->left) + TreeSize(root->right) + 1;
}
void preorder(struct TreeNode* root, int* a, int* i)
{
if (NULL == root)
return;
a[*i] = root->val;
(*i)++;
preorder(root->left, a, i);
preorder(root->right, a, i);
}
int* preOrderTraversal(struct TreeNode* root, int* returnSize)
{
*returnSize = TreeSize(root);
int* a = (int*)malloc(*returnSize * sizeof(int));
int i = 0;
preorder(root, a, &i);
return a;
}
T6、二叉树的前序遍历构建,中序遍历打印
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef char BTDataType;
typedef struct BinaryTreeNode
{
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
BTDataType data;
}BTNode;
BTNode* BuyNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
assert(node);
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
BTNode* CreateTree(char* str, int* pi)
{
if ('#' == str[*pi])
{
(*pi)++;
return NULL;
}
BTNode* root = BuyNode(str[*pi]);
(*pi)++;
root->left = CreateTree(str, pi);
root->right = CreateTree(str, pi);
return root;
}
void InOrder(BTNode* root)
{
if (NULL == root)
return;
InOrder(root->left);
printf("%c ", root->data);
InOrder(root->right);
}
int main()
{
char str[100];
scanf("%s", str);
int i = 0;
BTNode* root = CreateTree(str, &i);
InOrder(root);
return 0;
}