Given a binary tree, flatten it to a linked list in-place. (Medium)
For example,
Given
1 / 2 5 / \ 3 4 6
The flattened tree should look like:
1 2 3 4 5 6
分析:
将树的问题和链表插入问题结合。对于每个节点,寻找左子树的最右端,它应该是左子树前序遍历的最后一位,也就是生成链表中,右子树根节点的前一位。
按照链表插入的方法处理即可。
代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode* root) { 13 if (root == nullptr) { 14 return; 15 } 16 while (root != nullptr) { 17 if (root -> left != nullptr) { 18 TreeNode* temp = root -> left; 19 while (temp -> right != nullptr) { 20 temp = temp -> right; 21 } 22 temp -> right = root -> right; 23 root -> right = root -> left; 24 root -> left = nullptr; 25 } 26 root = root -> right; 27 } 28 } 29 };
时间: 2024-10-06 05:56:50