劍指Offer: 二叉樹的深度、平衡二叉樹
阿新 • • 發佈:2019-01-26
二叉樹的深度
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。
/*
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;
depth=0;
getDepth(pRoot,1);//引數對應相應高度值
return depth;
}
private:
void getDepth(TreeNode *root,int n){
if(root->left) getDepth(root->left,n+1);
if(root->right) getDepth(root->right,n+1);
if(!(root->left||root->right)) depth=max(depth,n);
}
int depth;
};
平衡二叉樹
輸入一棵二叉樹,判斷該二叉樹是否是平衡二叉樹。
它是一 棵空樹或它的左右兩個子樹的高度差的絕對值不超過1,並且左右兩個子樹都是一棵平衡二叉樹。
求深度,求的時候要及時判斷。
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if(!pRoot) return true;
if(getHeight(pRoot)==-1) return false;
return true;
}
private :
int getHeight(TreeNode *root){
int left{0},right{0};
if(root->left) left=getHeight(root->left);
if(left==-1) return -1;
if(root->right) right=getHeight(root->right);
if(right==-1||abs(right-left)>1) return -1;
return max(left,right)+1;
}
};