LeetCode: 114. Flatten Binary Tree to Linked List
程序员文章站
2022-03-07 23:40:14
...
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;
}
};
推荐阅读
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
114. Flatten Binary Tree to Linked List(二叉树展开为链表)
-
Leetcode Flatten Binary Tree to Linked List
-
【leetcode】114. 二叉树展开为链表(Flatten Binary Tree to Linked List)(DFS)
-
Flatten Binary Tree to Linked List
-
【python/M/114】Flatten Binary Tree to Linked List
-
【LeetCode】convert-sorted-list-to-binary-search-tree
-
LeetCode: 114. Flatten Binary Tree to Linked List
-
114. Flatten Binary Tree to Linked List
-
LeetCode 114 Flatten Binary Tree to Linked List