标签:
今天做了一题求二叉树节点的最大距离,顺便写了下二叉树的建立,遍历的过程。
我觉得这题的主要思想是深度遍历+动态规划,我们在深度遍历的过程中,对于某一个子树,求出左右子树叶子节点到根节点的最大距离,进而求出经过根节点的最大距离。 最后求出所有子树经过根节点的最大距离。就是这个题目的最终结果。代码如下:
//二叉树的建立,以及遍历 //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 -1 void 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 << " "; } 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 << "GetMaxNodeMaxDistance:" << endl; GetMaxNodeMaxDistance(Root); cout << max_distance << endl; system("pause"); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/king__moving/article/details/48025457