面试题 17.12. BiNode

本文旨在对于个人知识的梳理以及知识的分享,如果有不足的地方,欢迎大家在评论区指出


题目描述

二叉树数据结构TreeNode可用来表示单向链表(其中left置空,right为下一个链表节点)。实现一个方法,把二叉搜索树转换为单向链表,要求依然符合二叉搜索树的性质,转换操作应是原址的,也就是在原始的二叉搜索树上直接修改。

返回转换后的单向链表的头节点。

注意:本题相对原题稍作改动
示例:

输入: [4,2,5,1,3,null,6,0]
输出: [0,null,1,null,2,null,3,null,4,null,5,null,6]

提示:

  • 节点数量不会超过 100000。
题目链接
题目分析

题目中所给的是一颗二叉搜索树,我们可以发现转化成的单向链表是有序的,也就是该二叉搜索树的中序遍历,这里可以用一个简单的案例模拟一下该过程:
在这里插入图片描述
所对应的操作也就是tail.right = root; tail = tail.right; root.left=null,所以我们只需要中序遍历该二叉搜索树,然后执行上面代码的操作就可以将该二叉搜索树转化为一个单向链表

解题思路

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def convertBiNode(self, root: TreeNode) -> TreeNode:
        head, tail = None, None
        
        def dfs(root):
            nonlocal tail, head

            if not root:
                return
            dfs(root.left)
            if not tail:
                head = root
                tail = head
            else:
                tail.right = root
                tail = tail.right
            root.left = None
            dfs(root.right)
        dfs(root)
        return head

Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private TreeNode head, tail;

    private void dfs(TreeNode root){
        if(root == null) return;

        dfs(root.left);
        if(tail == null){
            head = root;
            tail = head;
        }else{
            tail.right = root;
            tail = tail.right;
        }
        root.left = null;
        dfs(root.right);
    }

    public TreeNode convertBiNode(TreeNode root) {
        dfs(root);
        return head;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值