//二叉树的数据结构
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
//二叉树的数据结构
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
//二叉树的数据结构
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
//实现,递归遍历二叉树的左子树,右子树,取子树深度大值,再加上子树与根节点的距离1,即为这颗二叉树的深度
class
Solution {
public
:
int
TreeDepth(TreeNode* pRoot)
{
if
(pRoot == NULL)
return
0
;
return
max(TreeDepth(pRoot->left),TreeDepth(pRoot->right)) +
1
;
}
};
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。(
平
衡二叉树
是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树)
class
Solution {
public
:
bool IsBalanced_Solution(TreeNode* pRoot) {
//基本情况
if
(pRoot == NULL)
return
true
;
int
BF = TreeDepth(pRoot->left) - TreeDepth(pRoot->right);
if
(BF < -
1
|| BF >
1
)
return
false
;
if
(IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right))
return
true
;
return
false
;
}
};
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
举例说明:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \11 9 7 5
//实现,从上而下,逐层交换
class
Solution {
public
:
void
Mirror(TreeNode *pRoot) {
if
(pRoot == NULL)
return
;
TreeNode *temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
以上编程题目摘自牛客网