关于二叉树,建立、遍历、求节点最大距离

来源:互联网 发布:企业画像 大数据 编辑:程序博客网 时间:2024/06/06 19:16
         今天做了一题求二叉树节点的最大距离,顺便写了下二叉树的建立,遍历的过程。  我觉得这题的主要思想是深度遍历+动态规划,我们在深度遍历的过程中,对于某一个子树,求出左右子树叶子节点到根节点的最大距离,进而求出经过根节点的最大距离。 最后求出所有子树经过根节点的最大距离。就是这个题目的最终结果。代码如下: //二叉树的建立,以及遍历//16 14 8 2 -1 -1 4 -1 -1 7 1 -1 -1 -1 10 9 -1 -1 3 -1 -1//16 14 8 2 -1 -1 4 -1 -1 7 1 -1 -1 -1 -1void  BuildBTree(BTreeNode* &pRoot){int nTemp;cin >> nTemp;if (nTemp == -1){pRoot = NULL;}else{pRoot = new BTreeNode();pRoot->nValue = nTemp;BuildBTree(pRoot->pLeft);BuildBTree(pRoot->pRight);}}void PreOrderBTree(BTreeNode* pRoot){if (pRoot == NULL){return;}cout << pRoot->nValue << " ";PreOrderBTree(pRoot->pLeft);PreOrderBTree(pRoot->pRight);}void MidOrderBTree(BTreeNode* pRoot){if (pRoot == NULL){return;}MidOrderBTree(pRoot->pLeft);cout << pRoot->nValue << " ";MidOrderBTree(pRoot->pRight);}void PostOrderBTree(BTreeNode* pRoot){if (pRoot == NULL){return;}PostOrderBTree(pRoot->pLeft);PostOrderBTree(pRoot->pRight);cout << pRoot->nValue << " ";}//层次遍历 也就是广度优先遍历void VisitByLevel(BTreeNode* pRoot){if (pRoot == NULL){return;}queue<BTreeNode*> treeQueue;treeQueue.push(pRoot);while(!treeQueue.empty()){BTreeNode* pNode = treeQueue.front();cout << pNode->nValue  << " ";treeQueue.pop();if (pNode->pLeft != NULL){treeQueue.push(pNode->pLeft);}if (pNode->pRight != NULL){treeQueue.push(pNode->pRight);}}}int  GetMaxNodeMaxDistance(BTreeNode* pRoot){if (pRoot == NULL){return -1;}//左子树叶子结点到根结点的最大距离int max_left_distance = GetMaxNodeMaxDistance(pRoot->pLeft);//右子树叶子结点到根结点的最大距离int max_right_distance = GetMaxNodeMaxDistance(pRoot->pRight);//每个子树节点的最大距离int max_root_distance = max_left_distance + max_right_distance + 2;//比较每个子树节点的最大距离if (max_root_distance > max_distance){max_distance = max_root_distance;}return max_left_distance > max_right_distance ? max_left_distance+1 : max_right_distance+1;}int max_distance = 0;int main(){BTreeNode* Root = NULL;BuildBTree(Root);cout << "----------------Build End------------------" << endl;system("pause");cout << "PreOrderBTree:" << endl;PreOrderBTree(Root);cout << endl << "MidOrderBTree:" << endl;MidOrderBTree(Root);cout << endl << "PostOrderBTree:" << endl;PostOrderBTree(Root);cout << endl << "VisitByLevel:" << endl;VisitByLevel(Root);cout << endl << "GetMaxNodeMaxDistance:" << endl;GetMaxNodeMaxDistance(Root);cout << max_distance << endl;system("pause");        return 0;}

0 0
原创粉丝点击