您的位置:首页 > 其它

二叉查找树转为双向链表

2012-05-23 14:56 169 查看
对于二叉查找树本能的想到了中序遍历,中序遍历二叉树的结果是有序的,只要使用非递归中序遍历,中间稍作修改应该就可以。这个是第一反应,觉得应该不难。不过还是,网上搜索一下,在网易何海涛的技术博客中看到,关于递归的解法。这个方法虽然有些耗资源,但是我觉得第一个 想到的应该是这一个,应为二叉树本来就是递归结构,二叉树很多问题的解决都是从递归入手。下面还是梳理一下这两个思路:1、非递归方法:中序遍历二叉查找树的结果是有序的,写出二叉树的中序非递归算法,在每次访问该节点的时候,改为将节点加入链表。2、递归方法:先将左子树形成链表,返回该链表的最后一个节点;再将右子树形成链表,并返回该链表的第一个节点;将左子树链表、节点、右子树链表连接起来,形成整个链表。第一种思路代码:
Node* Tree::toList()
{
stack<Node *> stack;
Node *p = root;
Node *head = 0;
Node *tail = 0;
while (p != 0 || !stack.empty()) {
while (p != 0) {
stack.push(p);
p = p->left;
}

p = stack.top();
stack.pop();
if (head == 0) {
head = p;
tail = p;
} else {
tail->right = p;
p->left = tail;
tail = p;
}
p = p->right;
}
return head;
}
第二种思路的代码:
Node * Tree::convert(Node *node, bool isRight){if (node == 0)return 0;Node *pleft = 0;Node *pright = 0;if (node->left != 0) {pleft = convert(node->left, false);}if (pleft != 0) {node->left = pleft;pleft->right = node;}if (node->right != 0) {pright = convert(node->right, true);}if (pright != 0) {node->right = pright;pright->left = node;}Node *ptem;if (isRight) {while (node->left)node = node->left;ptem = node;} else {while (node->right != 0)node = node->right;ptem = node;}return ptem;}
Node * Tree::convert(){return convert(root, true);}
参考:http://zhedahht.blog.163.com/blog/static/254111742007127104759245/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: