二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
如果一棵树为空,那么它的深度为0。如果一棵树只有一个结点,它的深度为1。如果根结点只有做子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度就是其右子树的深度加1。如果既有左子树又有右子树,那么树的深度就是其左右子树中深度的较大值再加1。
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return 1+(left>right?left:right);
}
判断一棵二叉树是否是平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路一:
在遍历树的每个结点的时候,调用函数TreeDepth得到它的左右子树深度。如果每个结点的左右子树深度相差都不超过1,按照定义,它就是一棵平衡二叉树。
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot)
return 0;
int leftDepth = TreeDepth(pRoot->left);
int rightDepth = TreeDepth(pRoot->right);
return leftDepth>rightDepth?leftDepth+1:rightDepth+1;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot)
return true;
int leftDepth = TreeDepth(pRoot->left);
int rightDepth = TreeDepth(pRoot->right);
if(abs(leftDepth-rightDepth)>1)
return false;
return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
}
思路一优化:
class Balance {
public:
bool isBalance(TreeNode* root) {
// write code here
return checkHeight(root) == -1?false:true;
}
int checkHeight(TreeNode* root)
{
if(!root)
return 0;
int leftHeight = checkHeight(root->left);
if(leftHeight == -1)
{
return -1;
}
int rightHeight = checkHeight(root->right);
if(rightHeight == -1)
{
return -1;
}
if(abs(leftHeight-rightHeight) >1)
{
return -1;
}
else
{
return max(leftHeight,rightHeight)+1;
}
}
};
思路二:
如果我们用后序遍历的方式遍历二叉树的每个结点,那么在遍历到一个结点之前我们就已经遍历了它的左右子树。只要在遍历每个结点的时候记录它的深度,我们就可以一边遍历以便判断每个结点是不是平衡的。
bool isBalanced(TreeNode* pRoot,int& pDepth)
{
if(!pRoot)
{
pDepth = 0;
return true;
}
int left=0;
int right = 0;
if(isBalanced(pRoot->left,left) && isBalanced(pRoot->right,right))
{
if(abs(left-right)<=1)
{
pDepth = 1+(left>right?left:right);
return true;
}
}
return false;
}
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return isBalanced(pRoot,depth);
}