剑指offer
二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
解法1:层次遍历
第一解法是利用递归调用,另一种解法是利用树的层次遍历
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==nullptr) return 0;
queue<TreeNode*>que;
que.push(pRoot);
int level=0;
while(!que.empty()){
int sz=que.size();//记录下一层节点的数目
while(sz--){
TreeNode *tmp=que.front();
que.pop();
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
}
level++;
}
return level;
}
};
解法2:递归调用
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int left_val=TreeDepth(pRoot->left);
int right_val=TreeDepth(pRoot->right);
return max(left_val,right_val)+1;
}
};
平衡二叉树
题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树平衡二叉树(Balanced
Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
解题思路
利用左右子树的深度不小于1,直接调用上面一题计算树的深度的代码,然后还要判断左右子树是否为平衡二叉树。
class Solution {
public:
int TreeDepth(TreeNode *pRoot){
if(pRoot==nullptr) return 0;
return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(pRoot==nullptr) return true;
int val=abs(TreeDepth(pRoot->left)-TreeDepth(pRoot->right));
return val<=1&&IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
};