BM30 二叉搜索树与双向链表

19 篇文章 0 订阅

在这里插入图片描述
解题思路:中序遍历即可,一直往左找,直至左孩子为空,这个节点就是要返回的链表头节点,pre不为空的时候就让pre.rihgt=当前节点,当前节点.left=pre即可,时间复杂度O(N),空间复杂度O(1)
这里说明一下:最终若返回 pre,那么是降序排列,题干要求升序,故保存第一个节点,返回root节点即可

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    TreeNode root = null;
    TreeNode pre = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        //从小到大->二叉搜索树的中序遍历
        Convert(pRootOfTree.left);
        if (root == null) {
            root = pRootOfTree;
        }
        if (pre != null) {
            pre.right = pRootOfTree;
            pRootOfTree.left = pre;
        }
        pre = pRootOfTree;
        Convert(pRootOfTree.right);
        //返回头节点
        return root;
    }
}

解法二: 也可以用非递归的方法,不过需要栈将节点给保存起来,时间复杂度O(N),空间复杂度O(N)

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (pRootOfTree != null) {
            stack.push(pRootOfTree);
            pRootOfTree = pRootOfTree.left;
        }

        //要返回的头节点
        TreeNode root = stack.pop();
        TreeNode pre = root;
        TreeNode cur = root.right;
        while (!stack.isEmpty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            cur.left = pre;
            pre.right = cur;
            pre = cur;
            cur = cur.right;
        }

        //返回头节点
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值