求二叉树的深度
思路:
分别递归左右子树,深度=左右子树中大的一个+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==NULL)
{
return 0;
}
int leftDepth=TreeDepth(pRoot->left);
int rightDepth=TreeDepth(pRoot->right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
};
输入一颗二叉树的根节点,判断该树是不是平衡二叉树
思路:
递归每一层都分别算出左右子树的高度,比较,看是否平衡
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
//判断平衡,比较高度
if(pRoot==NULL)
{
return true; //空树是平衡的二叉树
}
int leftDep=TreeDepth(pRoot->left);
int rightDep=TreeDepth(pRoot->right);
int dif=leftDep-rightDep;
if(dif>1||dif<-1)
{
return false;
}
return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
}
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
{
return 0;
}
int leftDepth=TreeDepth(pRoot->left);
int rightDepth=TreeDepth(pRoot->right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
};