114. Flatten Binary Tree to Linked List

本文详细解析了二叉树扁平化的三种高效算法:递归法、迭代法(使用栈)及Morris遍历。通过具体代码实现,展示了如何将二叉树转换为链表,同时保持节点的相对顺序,且不使用额外的数据结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

在这里插入图片描述

方法思路

Approach1:

class Solution{
    //Runtime: 6 ms, faster than 99.92%
    //Memory Usage: 39.2 MB, less than 5.09%
  private TreeNode next = null;
  public void flatten(TreeNode root) {
    if (root == null) return;
      
    flatten(root.right);
    flatten(root.left);
      
    root.right = next;
    root.left = null;
      
    next = root;
  }
}

Approach2:

class Solution{
    //it is DFS so u need a stack.    
    //Dont forget to set the left child to null, or u'll get TLE. (tricky!)
    //Runtime: 7 ms, faster than 75.79%
    //Memory Usage: 38.2 MB, less than 11.03%
    public void flatten(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stk = new Stack<TreeNode>();
        stk.push(root);
        while (!stk.isEmpty()){
            TreeNode curr = stk.pop();
            if (curr.right!=null)  
                 stk.push(curr.right);
            if (curr.left!=null)  
                 stk.push(curr.left);
            if (!stk.isEmpty()) 
                 curr.right = stk.peek();//查看此堆栈顶部的对象,而不从堆栈中删除它。 
            curr.left = null;  // dont forget this!! 
        }
    }
}

Approach3:

class Solution{
    //Runtime: 6 ms, faster than 99.92%
    //Memory Usage: 38.1 MB, less than 15.45% 
    //This solution is based on recursion. We simply flatten left and right subtree         and paste each sublist to the right child of the root. (don't forget to set left       child to null)
    public void flatten(TreeNode root) {
        if (root == null) return;
        
        TreeNode left = root.left;
        TreeNode right = root.right;
        
        root.left = null;
        
        flatten(left);
        flatten(right);
        
        root.right = left;
        TreeNode cur = root;
        while (cur.right != null) cur = cur.right;
        cur.right = right;
    }
}    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值