题目
将一棵二叉树按照前序遍历拆解成为一个假链表
。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
样例
1
1 2
/ \ 2 5 => 3
/ \ \ 3 4 6 4
5
6思路left = root->left;right = root->right;p = left->right的最后一个节点如果有left节点{ root->left = NULL; root->right = left; left->right = right;}然后递归C++代码
void flatten(TreeNode *root) { // write your code here if (root) { TreeNode* left = root->left; TreeNode* right = root->right; TreeNode* p = root; flatten(root->left); flatten(root->right); if (left) { p = root->left; while (p->right) { p = p->right; } root->left = NULL; root->right = left; p->right = right; } } }
时间: 2024-10-08 12:03:33