zoukankan      html  css  js  c++  java
  • 剑指offer---平衡二叉树

    方法一:基本方法 不做解释了

    class Solution 
    {
    public:
        int shendu(TreeNode* &root)
        {
            if(root==NULL)
            {
                return 0;
            }
            
            int zuozishu=shendu(root->left);
            int youzishu=shendu(root->right);
            
            return (zuozishu<youzishu?youzishu+1:zuozishu+1);
        }
        
        //遍历
        bool IsBalanced_Solution(TreeNode* pRoot)
        {
            if(pRoot==NULL)
            {
                return true;
            }
            
            int leftdepth=shendu(pRoot->left);
            int rightdepth=shendu(pRoot->right);
            int chazhi=abs(leftdepth-rightdepth);
            
            if(chazhi>1)
            {
                return false;
            }
            
            return(IsBalanced_Solution(pRoot->right)&&IsBalanced_Solution(pRoot->left));
        }
    };

    方法二:由于上述方法在求该结点的的左右子树深度时遍历一遍树,再次判断子树的平衡性时又遍历一遍树结构,造成遍历多次。因此方法二是一边遍历树一边判断每个结点是否具有平衡性。

    bool IsBalanced(BinaryTreeNode* pRoot, int* depth)  
    {  
        if(pRoot== NULL)  
        {  
            *depth = 0;  
            return true;  
        }  
      
        int nLeftDepth,nRightDepth;  
        bool bLeft= IsBalanced(pRoot->m_pLeft, &nLeftDepth);  
        bool bRight = IsBalanced(pRoot->m_pRight, &nRightDepth);  
          
        if (bLeft && bRight)  
        {  
            int diff = nRightDepth-nLeftDepth;  
            if (diff<=1 || diff>=-1)  
            {  
                *depth = 1+(nLeftDepth > nRightDepth ? nLeftDepth : nRightDepth);  
                return true;  
            }  
        }  
          
        return false;  
    }  
      
    bool IsBalanced(BinaryTreeNode* pRoot)  
    {  
        int depth = 0;  
      
        return IsBalanced(pRoot, &depth);  
    }  
  • 相关阅读:
    Haskell 编写几个递归函数 练习 typeclass 模式匹配等
    Haskell-chp01
    阉割的List
    实现简单的string类
    构造函数语义学——Copy Constructor 的构造操作
    BinarySearchTree-二叉搜索树
    对象模型
    二叉树的遍历
    带头尾结点的单链表
    Effective Modern C++ ——条款5 优先选择auto,而非显式型别声明
  • 原文地址:https://www.cnblogs.com/159269lzm/p/7269478.html
Copyright © 2011-2022 走看看