刷题 - 判断二叉树是否为平衡二叉树(附加求二叉树的深度/高度)

判断二叉树是否为平衡二叉树:

平衡二叉树的特点:二叉树中任意节点的左右子树高度差的绝对值<=1,因此本题的处理思路是比较直接的,就是从根节点开始遍历,判断所有节点的左右子树的高度差绝对值是否<=1。

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
         if(!pRoot)
               return true;
         int l = getDepth(pRoot->left);
         int r = getDepth(pRoot->right);
         if(l-r>1||l-r<-1)
             return false;
        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
         
    }
    int getDepth(TreeNode* pRoot){
        if(!pRoot) return 0 ;
            return 1+max(getDepth(pRoot->left),getDepth(pRoot->right));
    }
};

 

求树的高度

采用递归的处理思路进行求解,二叉树中以某个节点为根的子树的高度 = 1+max(左子树高度,右子树高度)。

class Solution {
public:
    int TreeDepth(TreeNode* pRoot){
        if(!pRoot) return 0 ;
            return 1+max(TreeDepth(pRoot->left),TreeDepth(pRoot->right));
    }
};

猜你喜欢

转载自blog.csdn.net/iea5357/article/details/106993043
今日推荐