LeetCode - 解题笔记 - 114 - Flatten Binary Tree to Linked List

Solution 1

这里面要求在既有链表结构上完成先序遍历的结构调整,也就是在调整过程中不改变树在先序遍历上的逻辑顺序,其实和 0094. Binary Tree Inorder Traversal 中的Morris遍历法在中序遍历上的思路一致,只需要修改遍历方法,以及最后的指针操作调整即可。

  1. 因为对右侧遍历不做任何操作,因此当当前节点左子树为空时,不做任何操作
  2. 找到当前节点右子树的理想前驱节点后,将右子树接到其右侧,然后将当前节点左子树切换到右子树(要求全是右子树),并将左子树置空
  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n为输入树的节点个数,完成调整需要完成一次遍历
  • 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个状态量,Morris法一个最大的优势就是可以不占用额外空间
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        auto now = root;
        while (now != nullptr) {
            if (now->left != nullptr) {
                auto pre = now->left;
                while (pre->right != nullptr) { pre = pre->right; }
                
                pre->right = now->right;
                now->right = now->left;
                now->left = nullptr;
            }
            
            now = now->right;
        }
    }
};

Solution 2

Solution 1的Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        now = root
        while now is not None:
            if now.left is not None:
                pre = now.left
                while pre.right is not None: pre = pre.right
                    
                pre.right = now.right
                now.right = now.left
                now.left = None
                
            now = now.right
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值