题目
剑指 Offer 36. 二叉搜索树与双向链表
我的思路
中序遍历一次,用一个辅助变量存储上一次访问的节点指针,访问时:
1.把上一次访问的节点的右节点指向当前节点
2.把当前节点的左指针指向上一次访问的节点
3.把当前节点设置为preNode
个人理解在这里遍历的同时修改树的结构是不会有影响的。因为当前访问的左子树上的节点一定在访问当前节点以前被访问,访问过的节点的右孩子会在双亲被访问后立即调用,所以修改右孩子指针也不影响。关键要最后把首尾节点连接起来
我的实现
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val) { val = _val; left = NULL; right = NULL; } Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; */ class Solution { Node* preNode; Node *tailNode; Node *headNode; void visit(Node *root){ //cout<<root->val<<endl; preNode->right = root; root->left = preNode; preNode = root; } void midSearch(Node *root){ if(root!=NULL){ if(root!=tailNode||root!=headNode){ midSearch(root->left); visit(root); if(root->right!=headNode) midSearch(root->right); } else{ visit(root); } } } public: Node* treeToDoublyList(Node* root) { tailNode = root; headNode = root; if(tailNode!=NULL){ while(tailNode->right!=NULL)tailNode = tailNode->right; while(headNode->left!=NULL)headNode = headNode->left; preNode = tailNode; midSearch(root); } return headNode; } };