面试题集锦之二叉树(连载中)
写在前面 最近开始关注找工作,所以四处搜索各种算法题来练手,希望有志同道合的朋友不吝赐教! 基础知识
面试题集锦
1 输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
遍历BS树中的最小节点(即循环搜索左子树),返回指向它的指针和它的父节点指针,从树中删除该节点
//二叉树 递归求镜像//10分钟 //一次通过#include <stdio.h>#include <string.h>struct BSTreeNode{int m_nValue; // value of nodestruct BSTreeNode *m_pLeft; // left child of node//错误1struct BSTreeNode *m_pRight; // right child of node}; void mirroritify(struct BSTreeNode *root){struct BSTreeNode *left;if(NULL==root->m_pLeft && NULL==root->m_pRight)return;mirroritify(root->m_pLeft);mirroritify(root->m_pRight);left = root->m_pLeft;root->m_pLeft = root->m_pRight;root->m_pRight = left;return;}int main(){int i;struct BSTreeNode node[10];struct BSTreeNode *root = &node[0];node[0].m_nValue = 8;node[0].m_pLeft = &node[1];node[0].m_pRight= &node[2];node[1].m_nValue = 6;node[1].m_pLeft = &node[3];node[1].m_pRight= &node[4];node[2].m_nValue = 10;node[2].m_pLeft = &node[5];node[2].m_pRight= &node[6];node[3].m_nValue = 5;node[3].m_pLeft = NULL;node[3].m_pRight= NULL;node[4].m_nValue = 7;node[4].m_pLeft = NULL;node[4].m_pRight= NULL;node[5].m_nValue = 9;node[5].m_pLeft = NULL;node[5].m_pRight= NULL;node[6].m_nValue = 11;node[6].m_pLeft = NULL;node[6].m_pRight= NULL;mirroritify(root);return 1;}