Convert Binary Search Tree to Doubly Linked List
题目:
Convert a binary search tree to doubly linked list with in-order traversal.
分析:
这道题目就强调一句话,就是传递参数的时候,void dfs(),里面一定是DoublyListNode* &curr。千万千万要引用!!!!
解法:
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
void dfs(TreeNode* root, DoublyListNode* &curr) {
if (root == NULL) {
return;
}
dfs(root->left, curr);
curr->next = new DoublyListNode(root->val);
curr = curr->next;
dfs(root->right, curr);
}
DoublyListNode* bstToDoublyList(TreeNode* root) {
// Write your code here
if (root == NULL) {
return NULL;
}
DoublyListNode dummy(0);
DoublyListNode* curr = &dummy;
dfs(root, curr);
return dummy.next;
}
};