《Cracking the Coding Interview》——第17章:普通题——题目13
2014-04-29 00:20
513 查看
2014-04-29 00:15
题目:将二叉搜索树展开成一个双向链表,要求这个链表仍是有序的,而且不能另外分配对象,就地完成。
解法:Leetcode上也有,递归解法。
代码:
题目:将二叉搜索树展开成一个双向链表,要求这个链表仍是有序的,而且不能另外分配对象,就地完成。
解法:Leetcode上也有,递归解法。
代码:
// 17.13 Flatten a binary search tree into a doubly linked list by inorder traversal order. // Use postorder traversal to do the flattening job. #include <cstdio> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {}; }; void flatten(TreeNode *&root, TreeNode *&left_most, TreeNode *&right_most) { if (root == nullptr) { left_most = right_most = nullptr; return; } TreeNode *ll, *lr, *rl, *rr; if (root->left != nullptr) { flatten(root->left, ll, lr); root->left = lr; lr->right = root; } else { ll = lr = root; } if (root->right != nullptr) { flatten(root->right, rl, rr); root->right = rl; rl->left = root; } else { rl = rr = root; } left_most = ll; right_most = rr; } void constructBinaryTree(TreeNode *&root) { int val; if (scanf("%d", &val) != 1) { root = nullptr; } else if (val == 0) { root = nullptr; } else { root = new TreeNode(val); constructBinaryTree(root->left); constructBinaryTree(root->right); } } void deleteList(TreeNode *&head) { TreeNode *ptr; while (head != nullptr) { ptr = head; head = head->right; delete ptr; } } int main() { TreeNode *root; TreeNode *left_most, *right_most; TreeNode *head; TreeNode *ptr; while (true) { constructBinaryTree(root); if (root == nullptr) { break; } flatten(root, left_most, right_most); head = left_most; for (ptr = head; ptr != nullptr; ptr = ptr->right) { printf("%d ", ptr->val); } putchar('\n'); deleteList(head); } return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第17章:普通题——题目2
- 《Cracking the Coding Interview》——第17章:普通题——题目9
- 《Cracking the Coding Interview》——第17章:普通题——题目3
- 《Cracking the Coding Interview》——第17章:普通题——题目10
- 《Cracking the Coding Interview》——第17章:普通题——题目11
- 《Cracking the Coding Interview》——第17章:普通题——题目4
- 《Cracking the Coding Interview》——第17章:普通题——题目12
- 《Cracking the Coding Interview》——第17章:普通题——题目5
- 《Cracking the Coding Interview》——第17章:普通题——题目14
- 《Cracking the Coding Interview》——第17章:普通题——题目6
- 《Cracking the Coding Interview》——第17章:普通题——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目8
- 《Cracking the Coding Interview》——第17章:普通题——题目1
- 《Cracking the Coding Interview》——第18章:难题——题目13
- 《Cracking the Coding Interview》——第13章:C和C++——题目4
- 《Cracking the Coding Interview》——第14章:Java——题目1
- 《Cracking the Coding Interview》——第18章:难题——题目7
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- 《Cracking the Coding Interview》——第5章:位操作——题目5
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目3