看起来很难,但是仔细想一下,实质就是二叉树的中序遍历的问题,中序遍历有递归和非递归(至少两种写法)。
递归:
class Solution { public: Node *prev; //实质是指向最后一个元素的指针 Node* treeToDoublyList(Node* root) { if (root==NULL) return NULL; Node *dummy=new Node(0,NULL,NULL); prev = dummy; inorder(root); prev->right = dummy->right; dummy->right->left = prev; return dummy->right; } void inorder(Node *root){ if (root==NULL) return; inorder(root->left); prev->right = root; root->left = prev; prev = root; inorder(root->right); } };
非递归
class Solution { public: Node *prev; //实质是指向最后一个元素的指针 Node* treeToDoublyList(Node* root) { if (root==NULL) return NULL; stack<Node *> s; Node *dummy=new Node(0,NULL,NULL); Node *p=root, *prev=dummy; while (!s.empty() || p!=NULL){ while (p){ s.push(p); p = p->left; } p = s.top(), s.pop(); prev->right = p; p->left = prev; prev = p; p = p->right; } prev->right = dummy->right; dummy->right->left = prev; return dummy->right; } };
class Solution { public: Node *prev; //实质是指向最后一个元素的指针 Node* treeToDoublyList(Node* root) { if (root==NULL) return NULL; Node *dummy=new Node(0,NULL,NULL); Node *prev=dummy; stack<Node *> s({root}); unordered_map<Node *,int> hash; while (!s.empty()){ Node *cur=s.top(); s.pop(); if (hash[cur]==0){ ++hash[cur]; s.push(cur); if (cur->left) s.push(cur->left); }else{ prev->right = cur; cur->left = prev; prev = cur; if (cur->right) s.push(cur->right); } } prev->right = dummy->right; dummy->right->left = prev; return dummy->right; } };
Divide and Conquer
原文地址:https://www.cnblogs.com/hankunyan/p/9532493.html
时间: 2024-09-30 13:49:08