求二叉树中两个节点的最远距离
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
计算一个二叉树的最大距离有两个情况:
情况A: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
情况B: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
思路:
1,后序遍历每一节点,找出该节点到最右边的距离以及最左边的距离;
2,找到之和最大的即可。
//需保存左子树中最长距离、右子树最长距离和当前树的深度。
//以下提供两种方法。
#include<iostream>#include<stack>usingnamespacestd;intmax(intl,intr){returnl>r?l:r;}structBinaryTreeNode{intdata;BinaryTreeNode*left;BinaryTreeNode*right;BinaryTreeNode(intx):data(x),left(NULL),right(NULL){}};classBinaryTree{protected:BinaryTreeNode*_root;BinaryTreeNode*_CreateBinaryTree(int*arr,int&index,intsize){BinaryTreeNode*root=NULL;if(index<size&&arr[index]!='#'){root=newBinaryTreeNode(arr[index]);root->left=_CreateBinaryTree(arr,++index,size);root->right=_CreateBinaryTree(arr,++index,size);}returnroot;}public:BinaryTree():_root(NULL){}BinaryTree(int*arr,intsize){intindex=0;_root=_CreateBinaryTree(arr,index,size);}/*intMaxTwoNodeDistance(){if(_root==NULL){return0;}intmaxDistance=0;_Distance(_root,maxDistance);returnmaxDistance;}*/intMaxTwoNodeDistance(){if(_root==NULL)return0;intmaxLeft=0;intmaxRight=0;return_Distance(_root,maxLeft,maxRight);}intHeight(){return_Height(_root);}voidPreOrder_Non(){if(_root==NULL)return;BinaryTreeNode*cur=_root;stack<BinaryTreeNode*>s;s.push(_root);while(!s.empty()){cur=s.top();printf("%d",cur->data);s.pop();if(cur->right)s.push(cur->right);if(cur->left)s.push(cur->left);}cout<<endl;}protected:int_Distance(BinaryTreeNode*root,int&left,int&right){if(root==NULL){left=0;right=0;return0;}intmll,mlr,mrl,mrr,dl,dr;if(root->left==NULL){left=0;dl=0;}else{dl=_Distance(root->left,mll,mlr);left=max(mll,mlr)+1;}if(root->right==NULL){right=0;dr=0;}else{dr=_Distance(root->right,mrl,mrr);right=max(mrl,mrr)+1;}returnmax(max(dl,dr),left+right);}/*int_Distance(BinaryTreeNode*root,int&max){if(root==NULL)return0;intmaxLeft=0;intmaxRight=0;if(root->left){maxLeft=_Distance(root->left,max);if(maxLeft>max)max=maxLeft;}if(root->right){maxRight=_Distance(root->right,max);if(maxRight>max)max=maxRight;}if(maxLeft+maxRight>max)max=maxLeft+maxRight;returnmaxLeft>maxRight?maxLeft+1:maxRight+1;}*/int_Height(BinaryTreeNode*root){if(root==NULL)return0;intleft=_Height(root->left);intright=_Height(root->right);returnleft>right?left+1:right+1;}};intmain(){intarr1[]={1,2,4,5,'#','#','#',7,'#','#',3,'#',6};intarr2[]={1,2,3,4,'#','#','#',5,'#',6};BinaryTreet1(arr1,sizeof(arr1)/sizeof(arr1[0]));t1.PreOrder_Non();cout<<t1.MaxTwoNodeDistance()<<endl;BinaryTreet2(arr2,sizeof(arr2)/sizeof(arr2[0]));t2.PreOrder_Non();cout<<t2.MaxTwoNodeDistance()<<endl;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。