一些笔试常考简单算法小结
来源:互联网 发布:天津市软件学院怎么样 编辑:程序博客网 时间:2024/04/30 00:24
1.链表逆转
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) {}};
0 0
- 一些笔试常考简单算法小结
- 这几天笔试常考算法
- 笔试面试常考排序算法总结
- 四种简单的排序算法 -----笔试常考非常有用
- 前端笔试常考
- 一些应届IT求职常考的笔试题举例
- 一些应届IT求职常考的笔试题举例
- 模拟一些字符串库函数(笔试常考)
- 笔试面试常考的一些小知识
- 【备忘】公司笔试常考算法重点简介
- 笔试常考排序算法(冒泡选择)
- SQL常考笔试题
- 嵌入式笔试常考题目
- 数据库常考笔试题
- 计算机网络笔试面试常考
- 数据库常考笔试题
- Java笔试常考知识点
- C++ 常考算法
- Git 常用命令方法总结
- 微信硬件蓝牙开发指南
- 高焕堂视频学习笔记:从架构到代码的演练
- 花花的music1
- oracle 导入可执行文件 imp exe
- 一些笔试常考简单算法小结
- iOS进度管理NSProgress类简单实用实例
- Java 类注释模板
- 欢迎使用CSDN-markdown编辑器
- relation from “X“ to“Y ”would cause an Invalid circular inheritance /realization combination
- 【C++11新特性】 C++11智能指针之shared_ptr
- Links Auto Replacer 自动给文章的关键词添加链接
- Android 表情功能的完整处理方案
- 模板类的继承