Flatten Binary Tree to Linked List
程序员文章站
2022-04-27 08:52:06
...
解析:将二叉树平铺成list链表的形式
第一种解法:
1.利用先序遍历,将每个节点的值保存在res数组当中
2.根据res数组中的值重新创建一个新的链表形式的二叉树,将其赋给root节点
优点:无需对指针进行复杂的操作
缺点:容易想到,当要花费大量的额外空间,然而递归的方法我无法设计出来,哎~~~~
/**
* 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) {
vector<int> res;
DFS(root, res);
TreeNode* new_root = root;
for (int i = 1; i < res.size(); ++i){
TreeNode* t = new TreeNode(res[i]);
new_root->left = NULL;
new_root->right = t;
new_root = t;
}
}
void DFS(TreeNode* root, vector<int>& res){
if (root != NULL){
res.push_back(root->val);
DFS(root->left, res);
DFS(root->right, res);
}
}
};
第二种解法
这种方法提供了一种特别好的递归设计思路,不过不是很容易实现
整体思想:将左边的节点依次链接到右节点的前面
/**
* 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) return;
if (root->left) flatten(root->left);
if (root->right) flatten(root->right);
TreeNode* t = root->right; //因为root节点在移动,所以得先保存右节点
root->right = root->left; //将左节点放在右节点的前面
root->left = NULL; //将左节点置空
while (root->right) root = root->right; //取右节点的最后一个节点
root->right = t; //将最后一个节点的右指针指向右节点
}
};
推荐阅读
-
Flatten Binary Tree to Linked List
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
114. Flatten Binary Tree to Linked List(二叉树展开为链表)
-
109. Convert Sorted List to Binary Search Tree
-
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