二叉树展开为链表
题目描述
解题思路
个人AC
- 将左子树放在右子树的位置,并将左子树置空;
- 将原右子树放在原左子树的最右结点的右结点上;
- 考虑新的右子树的根节点,重复上述过程,直到新的右子树为null。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
helper(root);
}
private TreeNode helper(TreeNode root) {
if (root == null) return null;
TreeNode rightestOfLeft = helper(root.left);
TreeNode right = root.right;
if (rightestOfLeft != null) {
root.right = root.left;
rightestOfLeft.right = right;
root.left = null;
}
flatten(root.right);
// return the rightest child of the root
while (root != null && root.right != null) {
root = root.right;
}
return root;
}
}
时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn);
空间复杂度: O ( l o g n ) O(logn) O(logn)。
最优解
参考: LeetCode CN 题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode pre;
public void flatten(TreeNode root) {
if (root == null) return ;
flatten(root.right);
flatten(root.left);
root.right = pre;
root.left = null;
pre = root;
}
}
时间复杂度: O ( n ) O(n) O(n);
空间复杂度: O ( l o g n ) O(logn) O(logn)。

本文详细解析了如何将二叉树转换为链表,包括两种不同的算法实现:一种利用递归和辅助函数,时间复杂度为O(nlogn),另一种采用后序遍历优化,实现O(n)的时间复杂度。文章提供了完整的代码示例,帮助读者深入理解这一数据结构操作。
483

被折叠的 条评论
为什么被折叠?



