LeetCode: 114. Flatten Binary Tree to Linked List
LeetCode: 114. Flatten Binary Tree to Linked List
题目描述
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \ 2 5
/ \ \ 3 4 6
The flattened tree should look like:
1
\ 2
\ 3
\ 4
\ 5
\ 6
题目大意: 将给定的二叉树拉直成链表形式。
解题思路 —— 递归求解
先将左子树和右子树拉直成链表形式,然后将它们合并成一条链表。如:
原始二叉树
flatten(root->left)
: 拉直左子树
flatten(root->right)
:拉直右子树
合并左右子树
将右子树链接到左子树:
将左子树移动到右边:
AC 代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
public:
void flatten(TreeNode* root) {
if(root == nullptr) return;
// 分别对左右孩子处理
flatten(root->left);
flatten(root->right);
// 将右边孩子链接在左孩子后面
// 然后将左孩子移到右边
TreeNode** leftChildTreeLeaf = &(root->left);
while(*leftChildTreeLeaf != nullptr)
{
leftChildTreeLeaf = &(*leftChildTreeLeaf)->right;
}
*leftChildTreeLeaf = root->right;
root->right = root->left;
root->left = nullptr;
}
};