二叉树练习习题
前言
嗨,我是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。 ↩︎
