一些笔试常考简单算法小结
2016-12-01 17:05
281 查看
1.链表逆转
2.二叉树遍历
前序
中序
后序
深度优先遍历
广度优先遍历
二叉树的深度
判断是否平衡二叉树
其中,树的结构如下:
ListNode* ReverseList(ListNode* pHead) { //什么也不用检查 ListNode *pre = nullptr, *next = nullptr; while (pHead) { //获取后一个 next = pHead->next; //指针反转 pHead->next = pre; //pre和pHead向后滑动 pre = pHead; pHead = next; } return pre; }
2.二叉树遍历
前序
void PreOrderVistTree(TreeNode *root) { if (root == nullptr)return; cout << root->val << endl; PreOrderVistTree(root->left); PreOrderVistTree(root->right); }
中序
void InOrderVistTree(TreeNode *root) { if (root == nullptr)return; InOrderVistTree(root->left); cout << root->val << endl; InOrderVistTree(root->right); }
后序
void PostOrderVistTree(TreeNode *root) { if (root == nullptr)return; PostOrderVistTree(root->left); PostOrderVistTree(root->right); cout << root->val << endl; }
深度优先遍历
void DepthVistFirst(TreeNode* root) { stack<TreeNode*>s; s.push(root); while (!s.empty()) { root = s.top(); cout << root->val << endl; s.pop(); if (root->right != nullptr)s.push(root->right); if (root->left != nullptr)s.push(root->left); } }
广度优先遍历
void BroadVistFirst(TreeNode* root) { queue<TreeNode*>q; q.push(root); while (!q.empty()) { root = q.front(); cout << root->val << endl; q.pop(); if (root->left != nullptr)q.push(root->left); if (root->right != nullptr)q.push(root->right); } }
二叉树的深度
int TreeDepth(BinaryTreeNode* pRoot)//计算二叉树深度 { if(pRoot==NULL)//如果pRoot为NULL,则深度为0,这也是递归的返回条件 return 0; //如果pRoot不为NULL,那么深度至少为1,所以left和right=1 int left=1; int right=1; left+=TreeDepth(pRoot->left);//求出左子树的深度 right+=TreeDepth(pRoot->right);//求出右子树深度 return left>right?left:right;//返回深度较大的那一个 } //简化版 int TreeDepth(TreeNode* pRoot) { if(!pRoot) return 0 ; return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right)); }
判断是否平衡二叉树
bool IsBalanced(TreeNode* pRoot) { if (pRoot == NULL)return true; //分别求左右子树深度 int leftDepth = TreeDepth(pRoot->left); int rightDepth = TreeDepth(pRoot->right); int diff = rightDepth - leftDepth; //深度比较 if (diff>1 || diff<-1) return false; //递归比较判别 return IsBalanced(pRoot->left) && IsBalanced(pRoot->right); }
其中,树的结构如下:
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) :val(x), left(nullptr), right(nullptr) {} };
相关文章推荐
- 笔试题中的两道简单算法题(用C#实现)
- 【题目19】一些简单的算法练习题(1)
- 偶见一道华为笔试题(简单的题更显算法啊--不可忽视的数学)
- 水下图像增强相关算法的一个简单小结
- 四舍五入的一些简单写法(利用内置函数,算法2种写法)
- ZZ一些简单算法
- 一些简单的lua面试题,小算法,算不上算法的算法。。╮(╯▽╰)╭博主面试的辛酸旅程
- 一些笔试算法
- 我在北京找工作(四):java实现递归<1> 一些笔试题+常见算法
- 一些看起来简单做起来难的程序员笔试面试题集锦
- 【题目28】一些简单题的算法练习题(2)
- 最进2011校招笔试中遇到的一些算法c语言的
- 一些简单常用算法整理学习 转
- 一些简单的算法
- 一些简单的链表算法二
- 【题目9】一些简单的查找交换等算法
- 计算机视觉一些简单图片处理算法
- 一些简单的算法
- FIELD-SYMBOLS的一些简单使用小结
- 关于最近的一些笔试面试的小结