/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Tree {
public:
int treemin;
int treemax;
list<TreeNode *> _l1,_l2;
list<TreeNode *> _t;
Tree(){
treemin=INT_MAX;
treemax=INT_MIN;
}
void preorder(TreeNode *root){
if(root==NULL){
return ;
}
if(root->left==NULL&&root->right==NULL){ // 注意是叶子节点的最大值与最小值
if(root->val>treemax){
treemax=root->val;
}
if(root->val<treemin){
treemin=root->val;
}
}
preorder(root->left);
preorder(root->right);
}
bool FindPath(TreeNode *root,int expect,list<TreeNode *> &path,int currentsum){
currentsum+=root->val;
path.push_back(root);
if(root->left==NULL&&root->right==NULL&¤tsum==expect){
res.push_back(path);
}
if(root->left==NULL){
FindPath(root->left,expect,path,currentsum)
}
if(root->right==NULL){
FindPath(root->right,expect,path,currentsum)
}
path.pop_back();
}
bool getpath(TreeNode *root,int findval,list<TreeNode *> path){
if(root==NULL){
return 1;
}
path.push_back(root);
if(findval==root->val){
_t=path;
return 1;
}
getpath(root->left,findval,path);
getpath(root->right,findval,path);
return 0;
}
int getcommoncount(const list<TreeNode *> &path1,const list<TreeNode *> &path2){
int count=0;
list<TreeNode *>::const_iterator iter1=path1.begin();
list<TreeNode *>::const_iterator iter2=path2.begin();
while(iter1!=path1.end()&&iter2!=path2.end()){
if(*iter1==*iter2){
iter1++;
iter2++;
}else{
break;
}
}
//count+=1;
while(iter1!=path1.end()){
count++;
iter1++;
}
//count+=1;
while(iter2!=path2.end()){
count++;
iter2++;
}
return count;
}
int getDis(TreeNode* root) {
// write code here
if(root==NULL){
return 0;
}
preorder(root);
_l1.clear();
getpath(root,treemin,_l1);
_l1=_t;
_t.clear();
_l2.clear();
getpath(root,treemax,_l2);
_l2=_t;
//cout<<_l1.size()<<endl;
return getcommoncount(_l1,_l2);
}
};
二叉树中叶子节点中最大值和最小值之间的路径
猜你喜欢
转载自blog.csdn.net/u010325193/article/details/86190526
今日推荐
周排行