您的位置:首页 > 其它

一些笔试常考简单算法小结

2016-12-01 17:05 281 查看
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) {}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: