897-递增顺序搜索树

题目

897. 递增顺序搜索树 - 力扣(LeetCode) (leetcode-cn.com)

思路

本题目要求将一个二叉搜索树转换成顺序单链表。

一个问题:如果我们已经得到了一棵二叉搜索树的左子树和右子树转换得到的结果,如何计算最终结果呢?

        4
        |
   2----+----7
   |         |
1--+--3   6--+--8

对于根节点4,其左子树计算结果为1,2,3,右子树计算结果为6,7,8,我们只要用根节点4将左右子树的结果连接起来即得到最终的结果。为了将左右子树结果和本节点连接起来,需要左子树结果的尾结点和右子树结果的头节点,因此我们需要同时返回头节点和尾结点(通过引用)。

代码

class Solution {
public:
    TreeNode* increasingBST(TreeNode* root) {
        TreeNode *head, *tail;
        link(root, head, tail);
        return head;
    }

    void link(TreeNode* node, TreeNode* &head, TreeNode* &tail) {
        if (node == nullptr) {
            head = nullptr;
            tail = nullptr;
            return;
        }
        TreeNode *h, *t;
        link(node->left, h, t);
        if (h != nullptr) {
            head = h;
            t->right = node;
            node->left = nullptr;
            tail = node;
        } else {
            head = node;
            tail = node;
        }
        link(node->right, h, t);
        tail->right = h;
        if (t != nullptr) {
            tail = t;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值