二叉树练习习题

二叉树练习习题

前言

嗨,我是firdawn,本章将介绍一些二叉树练习习题,帮助我们巩固二叉树的知识点。下面是本章的思维导图,那么,让我们开始吧!

一,翻转二叉树

题目描述

翻转二叉树,是LeetCode上的一道题,题目要求为:给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

思路

题目要求我们翻转二叉树每一个子节点左右子树,因为它遍历了二叉树的每个节点,并且对每个节点都是翻转左右子树,那么我们可以用递归的方法实现,将二叉树分为根,左子树,右子树。对于当前节点,翻转它的左右子树,然后再翻转它的左子树和右子树。

解答代码

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

//  //前序遍历
// struct TreeNode* invertTree(struct TreeNode* root) {
//     if(root==NULL)
//     {
//         return NULL;
//     }
//     struct TreeNode* tmp=root->left;
//     root->left=root->right;
//     root->right=tmp;

//     invertTree(root->left);
//     invertTree(root->right);
//     return root;
// }


//后序遍历
struct TreeNode* invertTree(struct TreeNode* root){
if(root==NULL)
{
    return NULL;
}

struct TreeNode* tmp=root->right;
root->right=invertTree(root->left);
root->left=invertTree(tmp);

return root;

}

二,平衡二叉树

题目描述

平衡二叉树,题目要求为:给定一个二叉树,判断它是否是平衡二叉树[1](#1) 。

思路

因为它需要遍历二叉树所有节点,并且判断当前节点下的左右子树高度差值,所以我们同样可以用递归判断。二叉树分为根节点,左子树,右子树,我们可以在当前根节点下,判断左右子树高度差值是否满足不超过1的条件,如果满足就继续判断左右子树的下的子树高度差值,不满足就返回false。如果根节点下的左右子树差值满足并且左右子树的子树差值满足题目条件,那么就说明这棵树是平衡二叉树。

解答代码

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

int getDepth(struct TreeNode* root)
{
    if(root==NULL)
    {
        return 0;
    }
    int LeftDepth=getDepth(root->left);
    int rightDepth=getDepth(root->right);
    int Depth=LeftDepth>rightDepth?LeftDepth:rightDepth;//取左右子树深度更高的为子树深度

    return 1+Depth;
}

int absVal(int x,int y)
{
    return x>y?x-y:y-x;
}

bool isBalanced(struct TreeNode* root) {
    if(root==NULL)
    {
        return true;
    }

    int LeftDepth=getDepth(root->left);
    int rightDepth=getDepth(root->right);
    if(absVal(LeftDepth,rightDepth)>1)
    {
        return false;
    }
    return isBalanced(root->left) && isBalanced(root->right);
    
}

  1. 是指该树所有节点的左右子树高度相差不超过1。 ↩︎
相关推荐
2601_9499506312 小时前
练题簿小程序的 4 个功能,把学习资料变成题库
人工智能·小程序·刷题·练习·小程序推荐
2601_949950631 天前
错题总是反复错?用练题簿在线刷题,把复习重点找出来
人工智能·小程序·刷题·练习·小程序推荐
liangshanbo12153 天前
面试题:二叉树的遍历及使用场景
二叉树
a1879272183112 天前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树·树·bfs·算法讲解·树遍历
wabs66613 天前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
wabs66615 天前
关于二叉树【力扣100.相同的树的思考】
数据结构·c++·算法·leetcode·二叉树·递归法
wabs66617 天前
关于二叉树【力扣101.对称二叉树的思考】
数据结构·c++·算法·leetcode·二叉树
2601_9499506318 天前
练题簿:把备考资料装进小程序,随时开启高效在线刷题
人工智能·小程序·刷题·练习·小程序推荐
-dzk-21 天前
【二叉树】LC 236.二叉树的最近公共祖先
数据结构·二叉树