二叉树最近公共父节点
来源:互联网 发布:mac老是弹出垃圾网站 编辑:程序博客网 时间:2024/06/07 23:09
#include <bits/stdc++.h>using namespace std;struct TreeNode{ int val; TreeNode*left; TreeNode*right; TreeNode(int x): val(x),left(NULL),right(NULL) {}};int k;int x,y;void create(TreeNode*root,int n){ if(n==0)return; root->left=new TreeNode(root->val-pow(2,n-1)); root->right=new TreeNode(root->val+pow(2,n-1)); create(root->left,n-1); create(root->right,n-1);}//针对二叉排序树TreeNode*findTreeNode(TreeNode*root,int n){ if(root->val==n)return root; else if(root->val<n)return findTreeNode(root->right,n); else findTreeNode(root->left,n);}//方法一:针对所有二叉树结构,复杂度较高TreeNode*findCommonParent(TreeNode*root,TreeNode*p,TreeNode*q){ if(root==NULL||p==root||q==root)return root; TreeNode*leftNode=findCommonParent(root->left,p,q); TreeNode*rightNode=findCommonParent(root->right,p,q); if(leftNode&&rightNode)return root; else if(leftNode)return leftNode; else return rightNode;}//方法二:针对二叉树平排序结构,复杂度较低TreeNode*findCommonParent1(TreeNode*root,TreeNode*p,TreeNode*q){ int min,max; if(p->val<q->val)min=p->val,max=q->val; else min=q->val,max=p->val; while(root) { if(root->val>=min&&root->val<=max)return root; else if(root->val<min&&root->val<max)root=root->right; else root=root->left; } return NULL;}int main(){ while(cin>>k>>x>>y) { TreeNode*root=new TreeNode(pow(2,k-1)); create(root,k); TreeNode*p=findTreeNode(root,x); TreeNode*q=findTreeNode(root,y); TreeNode*commonParent=findCommonParent(root,p,q); cout<<"方法一:"<<commonParent->val<<endl; TreeNode*commonParent1=findCommonParent1(root,p,q); cout<<"方法二:"<<commonParent1->val<<endl; } return 0;}
阅读全文
0 0
- 二叉树最近公共父节点
- 二叉树最近公共父节点
- 二叉树查找最近公共父节点
- 二叉树--最近公共父节点
- 二叉树最近公共父节点
- 二叉树最近公共父节点
- 二叉树最近公共父节点
- 二叉树最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两个节点的最近公共父节点
- 二叉树中两节点最近公共父节点
- 算法题16 二叉树最近公共父节点
- 二叉树最近公共父亲节点
- 二叉树最近公共祖先节点
- Android 基于Google API的串口开发
- LoadRunner如何获取web_submit_data的返回值
- Android开发常用开源框架:图片处理
- Android ADB工具-管理设备/取设备硬件信息(一)
- winJay-简书笔记汇总
- 二叉树最近公共父节点
- Android Studio 中 Android Monitor 连接设备后 No Debuggable Applications 的解决
- PAT 1019. 数字黑洞 (20)
- android系统源码编译
- 待学习记录
- PAT 1035.插入与归并排序
- 关于listview的item的背景选择器
- 本地VideoFrame渲染二(VideoCapturer)
- Django 分页功能