0
点赞
收藏
分享

微信扫一扫

二叉树基础oj练习(单值二叉树、相同的树、二叉树的前序遍历)

讲了这么多数据结构相关的知识(可以看我的数据结构文章专栏):

抓紧刷题巩固一下了

目录

1.单值二叉树

题目描述

思路1

代码1

思路2

 代码2

2.相同的树

题目描述 

思路

代码

3.二叉树的前序遍历

代码

 思路


1.单值二叉树

965. 单值二叉树 - 力扣(LeetCode)

题目描述

思路1

代码1

bool isUnivalTree(struct TreeNode* root) {
    if(root==NULL)
    return true;
    if(root->left!=NULL&&root->left->val!=root->val)
    {
        return false;
    }
    if(root->right!=NULL&&root->right->val!=root->val)
    {
        return false;
    }
    return isUnivalTree(root->left)&&isUnivalTree(root->right);
}

思路2

 代码2

bool isUnivalTree(struct TreeNode* root) {
    if(root==NULL)//看根
    {
          return true;
    }
    if(root->left)//左子树不为空就先看左子树符合否
    {
        if(root->left->val!=root->val||!isUnivalTree(root->left))
        return false;
    }
    if(root->right)//右子树不为空
    {
        if(root->right->val!=root->val||!isUnivalTree(root->right))
        return false;
    }
    return true;
}

2.相同的树

100. 相同的树 - 力扣(LeetCode)

题目描述 

思路

先根和根比,比完再比左子树和右子树

代码

bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(p==NULL&&q==NULL)
    {
        return true;
    }
    if(p==NULL&&q!=NULL)
    {
        return false;
    }
    if(q==NULL&&p!=NULL)
    {
        return false;
    }
    if(p->val!=q->val)
    {
        return false;
    }
   bool left= isSameTree(p->left,q->left);
   bool right= isSameTree(p->right,q->right);
    return left&&right;
}


3.二叉树的前序遍历

144. 二叉树的前序遍历 - 力扣(LeetCode)

代码

int TreeSize(struct TreeNode* root)
{
    return root == NULL ? 0 : 1 + TreeSize(root->left) + TreeSize(root->right);
}

void preorder(struct TreeNode* root, int* a, int* i)
{
    if (root == NULL)
    {
        return;
    }
    a[*i] = root->val;
    (*i)++;
    preorder(root->left, a, i);
    preorder(root->right, a, i);
}

int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int n = TreeSize(root);
    *returnSize=n;
    int* a=(int*)malloc(sizeof(int)*n);
    int i=0;
    preorder(root,a,&i);
    return a;
}

 思路

举报

相关推荐

0 条评论