面试题55:二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
// 对每一个节点判断其左子节点与右子节点的深度;
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==nullptr)
return 0;
int nLeft=maxDepth(root->left);
int nRight=maxDepth(root->right);
return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
};
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
class Solution {
public:
// 求节点的深度
int TreeDepth(TreeNode* root){
if(root==nullptr)
return 0;
int nLeft=TreeDepth(root->left);
int nRight=TreeDepth(root->right);
return (nLeft>nRight)?(nLeft+1):(nRight+1);
}
// 遍历每个节点,判断其左子树和右子树深度是否相差>1
bool isBalanced(TreeNode* root) {
if(root==nullptr)
return true;
int left=TreeDepth(root->left);
int right=TreeDepth(root->right);
int diff=left-right;
if(diff>1 || diff <-1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
// 方法二:后序遍历+剪枝
class Solution {
public:
bool isBalanced(TreeNode* root) {
return recur(root) != -1;
}
int recur(TreeNode* root){
if(root==nullptr)
return 0;
int left=recur(root->left);
if(left==-1)
return -1;
int right=recur(root->right);
if(right==-1)
return -1;
return abs(left-right)<2?max(left,right)+1:-1; // 返回当前节点的深度;
}
};