1.二叉树的前序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int TreeeSize(struct TreeNode* root)
{
return root == NULL ? 0 : TreeeSize(root->left) + TreeeSize(root->right) + 1;
}
void Preorder(struct TreeNode* root , int *a , int * pi)
{
if(root == NULL)
return;
a[(*pi)++] = root->val;
Preorder(root->left , a , pi);
Preorder(root->right , a , pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
*returnSize = TreeeSize(root);
int *a = malloc(sizeof(int) * (*returnSize));
int i = 0;
Preorder(root , a , &i);
return a;
}
2.翻转二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root)
{
if (root == nullptr)
return nullptr;
TreeNode* left = invertTree(root->left);
TreeNode* right = invertTree(root->right);
root->left = right;
root->right = left;
return root;
}
};
3.另一棵树的子树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p==NULL && q == NULL)
return true;
if(p == NULL || q == NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left)
&&isSameTree(p->right,q->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot)
{
if(root == nullptr)
return false;
if(root->val == subRoot->val && isSameTree(root , subRoot))
return true;
return isSubtree(root->left,subRoot)
|| isSubtree(root->right,subRoot);
}
};