递归专项-114二叉树转为链表

在这里插入图片描述

该题目首先最简单的方法就是通过先序遍历将节点存放到一个List数组之中,然后,针对这个List数组在恢复成链表,但是这样子的话存储空间就会比较大,题目进阶希望使用原地算法O(1)的方式,这时该方案就不可取了。这里我们看一下如何解决。

在这里插入图片描述

我们针对任意一个当前节点,他只有左子树和右子树,我们希望找到左子树的先序遍历的最后一个节点,作为右子树的前驱节点,这样就将左子树右节点连在一起,符合我们的需求,后面就是递归在去处理右节点。 代码如下:

package leetcode.editor.cn;

import common.TreeNode;

public class P114FlattenBinaryTreeToLinkedList {
    public static void main(String[] args) {
        Solution solution = new P114FlattenBinaryTreeToLinkedList().new Solution();
        System.out.println("Hello world");
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
     if (root == null) {
         return;
     }
     preDfs(root);
    }



    /**
     *
     * @param node: 当前节点
     * @return 右子树前驱节点
     */
    public TreeNode preDfs(TreeNode node) {

        if (node.left == null && node.right == null) {
            return node;
        }
        TreeNode preNode = null;
        TreeNode right = node.right;
        if (node.left != null) {
            preNode = preDfs(node.left);
            right = node.right;
            node.right = node.left;
            preNode.right = right;
            node.left = null;
        }

        if (right != null) {
            preNode = preDfs(right);
        }

        return preNode;
    }


}
//leetcode submit region end(Prohibit modification and deletion)

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值