二叉树的深度 | 判断是否为平衡二叉树

判断二叉树深度

    int TreeDepth(TreeNode* pRoot)
    {
    if (pRoot==NULL)
        return 0;
        
    int left= TreeDepth(pRoot->left);
    int right= TreeDepth(pRoot->right);
        
    return  (left>right) ? (left+1) : (right+1);   
    }

判断平衡二叉树 (任意节点的左右子树深度相差不超过1 ;那么是)

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {//相差1 或者0

    if(pRoot==NULL)
       return true;
    //遍历当前节点深度
    int left= TreeDepth(pRoot->left);//左子树深度
    int right = TreeDepth(pRoot->right);//左子树深度     
       
        if(left-right>1||left-right<-1)
        {
            return false;  
        }
     return IsBalanced_Solution( pRoot->left)&&IsBalanced_Solution( pRoot->right); 
        
    }
    
    
    int TreeDepth(TreeNode* pRoot)
    {
    if (pRoot==NULL)
        return 0;
        
    int left= TreeDepth(pRoot->left);
    int right= TreeDepth(pRoot->right);
        
    return  (left>right) ? (left+1) : (right+1);   
    }
    
    
};

 

posted @ 2019-08-28 15:14  高颖1995  阅读(212)  评论(0编辑  收藏  举报