http://blog.csdn.net/zhaojinjia/article/details/11891523
來自劍指offer
求樹的深度
用遞歸做很簡單,只要知道遞歸出口語句的別寫錯。
- struct BinaryTreeNode
- {
- int m_Value;
- BinaryTreeNode* m_pLeft;
- BinaryTreeNode* m_pRight;
- };
- int TreeDepth(BinaryTreeNode* pRoot)
- {
- if (pRoot == NULL)
- return 0;
- int nLeftDepth = TreeDepth(pRoot->m_pLeft);
- int nRightDepth = TreeDepth(pRoot->m_pRight);
- return (nLeftDepth>nRightDepth)?(nLeftDepth+1):(nRightDepth+1);
- }
判斷該樹是否爲平衡二叉樹
方法一:調用上述函數求每個節點的左右孩子深度
- bool IsBalanced(BinaryTreeNode* pRoot)
- {
- if(pRoot== NULL)
- return true;
- int nLeftDepth = TreeDepth(pRoot->m_pLeft);
- int nRightDepth = TreeDepth(pRoot->m_pRight);
- int diff = nRightDepth-nLeftDepth;
- if (diff>1 || diff<-1)
- return false;
- return IsBalanced(pRoot->m_pLeft)&&IsBalanced(pRoot->m_pRight);
- }
方法二:由於上述方法在求該結點的的左右子樹深度時遍歷一遍樹,再次判斷子樹的平衡性時又遍歷一遍樹結構,造成遍歷多次。因此方法二是一邊遍歷樹一邊判斷每個結點是否具有平衡性。
- 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);
- }