二叉树面试题
来源:互联网 发布:人工智能辅助器具研发 编辑:程序博客网 时间:2024/04/29 07:38
1、>> 二叉树的后续遍历非递归void PostOrder_Nor()//后序遍历 非递归{if(_pRoot == NULL)return;stack<Node*> s;Node* pCur = _pRoot;Node* prev = NULL;//临时变量 保存刚刚访问过的节点while(pCur || !s.empty()){while(pCur)//保存左边路径上的节点{s.push(pCur);pCur = pCur->_pLeft;}if(!s.empty())//???{pCur = s.top();if(pCur->_pRight == NULL || pCur->_pRight == prev){cout<<pCur->_value<<" ";prev = pCur;s.pop();pCur = NULL;//}elsepCur = pCur->_pRight;}}}2、>> 判断一棵树是否为完全二叉树bool IsCompleteBinaryTree(){if(_pRoot == NULL)return true;queue<Node*> q; Node* pCur = _pRoot;q.push(pCur);bool flag = false;while(!q.empty()){pCur = q.front();if(flag){if(pCur->_pLeft || pCur->_pRight)return false;}else{if(pCur->_pLeft && pCur->_pRight){q.push(pCur->_pLeft);q.push(pCur->_pRight);}else if(pCur->_pLeft){q.push(pCur->_pLeft);flag = true;}else if(pCur->_pRight)return false;elseflag = true;}q.pop();}return true;}3、>> 根据前序和中序遍历结果重建二叉树4、>> 寻找二叉树中两个结点的公共祖先结点#include<iostream>using namespace std;#include<stack>#include<vector>typedef struct Node{char _data;Node* _pLeft;Node* _pRight;Node(char data):_data(data),_pLeft(NULL),_pRight(NULL){}~Node(){delete _pLeft;delete _pRight;}};Node* RebuildBinaryTree(char* PreOrder,char* InOrder,int n){if(n == 0)return NULL;char data = PreOrder[0];//根据前序创建根Node* node = new Node(data);int i = 0;for(i = 0; i<n && InOrder[i]!=data; i++);int Leftlen = i;//左子树长度int Rightlen = n-i-1;//不算中间的根节点 右子树长度if(Leftlen)//递归左子树node->_pLeft = RebuildBinaryTree(&PreOrder[1],&InOrder[0],Leftlen);if(Rightlen)//递归右子树node->_pRight = RebuildBinaryTree(&PreOrder[Leftlen+1],&InOrder[Leftlen+1],Rightlen);return node;}bool FindPath(Node* pRoot, vector<char> &path, char key)//找路径{if(pRoot == NULL)return false;path.push_back(pRoot->_data);if(pRoot->_data == key)return true;if(FindPath(pRoot->_pLeft,path,key)||FindPath(pRoot->_pRight,path,key))//在左右子树中找路径return true;path.pop_back();return false;}char FindLCA(Node* pRoot,char key1, char key2)//找最近公共祖先节点{vector<char> path1; vector<char> path2;bool find1 = FindPath(pRoot, path1, key1);bool find2 = FindPath(pRoot, path2, key2);if(find1&&find2){char ans;int i;for(i = 0; i<path1.size(); i++){if(path1[i]!=path2[i]) break; else ans = path1[i];} return ans;}return -1;}int main(){char s1[6] = {'a','b','d','c','e','f'};char s2[6] = {'d','b','a','e','c','f'};Node* node = RebuildBinaryTree(s1,s2,6); cout<<FindLCA(node,'e','d')<<endl;system("pause");return 0;}
2 0
- 二叉树面试题
- 【面试题】-二叉树
- 二叉树面试题
- 二叉树 面试题
- 二叉树面试题
- 二叉树面试题
- 二叉树面试题
- 【面试题】二叉树
- 【面试题】二叉树
- 二叉树面试题
- 二叉树面试题
- 二叉树面试题
- 二叉树面试题
- 二叉树面试题
- 二叉树面试题
- 某公司二叉树面试题
- 面试题(二叉树相关)
- 面试题(二叉树相关)
- 英文字母间出现不明空格
- 企业级加密文件系统eCryptfs使用及命令
- 深入分析Java使用+和StringBuilder进行字符串拼接的差异
- One meaning match many words
- Atcoder Grand Contest014题解
- 二叉树面试题
- Java读取excel中的数据
- python基础知识汇总
- Struts2和Hibernate原理与架构
- impdp create index parallel-数据泵并行创建索引
- nodejs环境下html的解析(宅男福利)
- [lintcode]最大数 Largest Number
- 最大熵模型
- DataTable 更改在有数据列的类型方法