求树的深度
用递归做很简单,只要知道递归出口语句的别写错。
- 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);
- }